Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sphinx and Autodoc generation #50

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,8 @@ cython_debug/
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

.idea/
.vscode/

*.json
*.toml
Expand Down
File renamed without changes.
20 changes: 20 additions & 0 deletions docs/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build

# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
35 changes: 35 additions & 0 deletions docs/make.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
@ECHO OFF

pushd %~dp0

REM Command file for Sphinx documentation

if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)

if "%1" == "" goto help

%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%

:end
popd
7 changes: 7 additions & 0 deletions docs/source/_static/css/custom.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@import 'material_sphinx.css';

.sig.sig-object.py{
font-feature-settings: "kern";
font-family: "Roboto Mono", "Courier New", Courier, monospace;
background: #f8f8f8;
}
41 changes: 41 additions & 0 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import os
import sys
sys.path.insert(0, os.path.abspath('../../masterbase'))

# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

project = 'Masterbase'
copyright = '2024 MegaAntiCheat'
author = 'Jayce, Flenser, Lilith, meat🥩'
release = '0.1'

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.napoleon',
'sphinx-pydantic'
]

templates_path = ['_templates']
exclude_patterns = []

# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = 'alabaster'
html_static_path = ['_static']


def setup(app):
app.add_css_file('css/custom.css')
20 changes: 20 additions & 0 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
.. Masterbase documentation master file, created by
sphinx-quickstart on Mon May 13 12:57:00 2024.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.

MegaAntiCheat Masterbase documentation
======================================

.. toctree::
:maxdepth: 2
:caption: Contents:

modules

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
61 changes: 61 additions & 0 deletions docs/source/masterbase.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
masterbase package
==================

Submodules
----------

masterbase.anomaly module
-------------------------

.. automodule:: masterbase.anomaly
:members:
:undoc-members:
:show-inheritance:

masterbase.app module
---------------------

.. automodule:: masterbase.app
:members:
:undoc-members:
:show-inheritance:

masterbase.guards module
------------------------

.. automodule:: masterbase.guards
:members:
:undoc-members:
:show-inheritance:

masterbase.lib module
---------------------

.. automodule:: masterbase.lib
:members:
:undoc-members:
:show-inheritance:

masterbase.registers module
---------------------------

.. automodule:: masterbase.registers
:members:
:undoc-members:
:show-inheritance:

masterbase.steam module
-----------------------

.. automodule:: masterbase.steam
:members:
:undoc-members:
:show-inheritance:

Module contents
---------------

.. automodule:: masterbase
:members:
:undoc-members:
:show-inheritance:
7 changes: 7 additions & 0 deletions docs/source/modules.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
masterbase
==========

.. toctree::
:maxdepth: 4

masterbase
4 changes: 3 additions & 1 deletion masterbase/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
"""Source code for API interaction."""
"""
Source code for API interaction.
"""
93 changes: 69 additions & 24 deletions masterbase/anomaly.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,40 @@
"""Anomaly detection for demo streams."""
"""
Anomaly detection for demo streams.

Classes:
- DetectionState

Functions:
- longest_zero_run
- likelihood
- nz_markov_likelihood
- transition_freqs

Misc variables:
- S_hat
"""

__author__ = "Flenser, Jayce"
__version__ = "1.0.0"

import os

import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, Field

S_hat: NDArray = np.load(os.path.join("masterbase", "S_hat.npy"))

S_hat: NDArray | None = None


def longest_zero_run(data: bytes) -> int:
"""Get the longest zero run of data.
"""
Get the longest zero run of data.

Args:
data: Input data stream
:param data: Input data stream
:type data: bytes
:return: longest zero run
:rtype: int
"""
array = np.frombuffer(data, dtype=np.uint8)
zero_mask = array == 0
Expand All @@ -27,31 +48,46 @@ def longest_zero_run(data: bytes) -> int:


def likelihood(p: NDArray, q: NDArray) -> float:
"""Determine the likelihood of an empirical frequency distribution under a prior discrete probability distribution.

Args:
p: Discrete prior distribution
q: Observed empirical distribution, normalized
"""
Determine the likelihood of an empirical frequency distribution under a prior discrete probability distribution.

:param p: Discrete prior distribution
:type p: NDArray
:param q: Observed empirical distribution, normalized
:type q: NDArray
:return: likelihood
:rtype: float
"""
return np.exp(np.sum(np.log(p + 1e-5) * q))


def nz_markov_likelihood(coocs: NDArray) -> float:
"""Determine the Markov likelihood of all byte-pair transitions, between *nonzero* bytes, e.g., as determined by `transition_freqs`.
"""
Determine the Markov likelihood of all byte-pair transitions, between *nonzero* bytes,
e.g., as determined by `transition_freqs`.

Args:
coocs: cooccurrences of successive octets (transition frequencies).
:param coocs: cooccurrences of successive octets (transition frequencies).
:type coocs: NDArray
:return: likelihood
:rtype: float
""" # noqa
global S_hat
if S_hat is None:
S_hat = np.load(os.path.join("data", "npy", "S_hat.npy"))

_S_hat, coocs = map(lambda a: a.reshape(-1)[1:], (S_hat, coocs)) # noqa
_S_hat, coocs = map(lambda a: a / a.sum(), (_S_hat, coocs)) # noqa
return float(likelihood(_S_hat, coocs))


def transition_freqs(data: bytes) -> NDArray:
"""Count the cooccurrences of successive octets (transition frequencies).
"""
Count the co-occurrences of successive octets (transition frequencies).

Args:
data: bytes, the input data stream
:param data: the input data stream
:type data: bytes
:return: Array of co-occurrences
:rtype: NDArray
"""
array = np.frombuffer(data, dtype=np.uint8)
i, j = array[:-1], array[1:]
Expand All @@ -61,23 +97,27 @@ def transition_freqs(data: bytes) -> NDArray:


class DetectionState(BaseModel):
"""Accumulate a trace of statistics for determining the likelihood of observed data under Markov transition frequencies present in valid data.

Args:
"""
Accumulate a trace of statistics for determining the likelihood of observed data under Markov transition
frequencies present in valid data.

Attributes:
length: The cumulative length of all inputs thus far.
likelihood: The cumulative probability of observing the input data under `S_hat` so far.
Comment on lines +100 to 105
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does sphinx not work with google-notypes docstring convention? Or just favoring this style?

longest_zero_run: The longest run of consecutive zeros observed in the input data chunks so far.
""" # noqa

length: int = Field(default=0)
likelihood: float = Field(default=0.0)
longest_zero_run: int = Field(default=0)

def update(self, data: bytes) -> None:
"""Update the current state trace with stats from the input data.
"""
Update the current state trace with stats from the input data.

Args:
data: bytes, input data whose likelihood to compute under the prior transition matrix to accumulate into statistics for the stream.
:param data: input data whose likelihood to compute under the prior transition matrix to accumulate
into statistics for the stream.
:type data: bytes
:return: None
""" # noqa
new_length = len(data) + self.length
new_likelihood = (
Expand All @@ -90,5 +130,10 @@ def update(self, data: bytes) -> None:

@property
def anomalous(self) -> bool:
"""Return if the current state is anomalous or not."""
"""
Return if the current state is anomalous or not.

:return: true if likelihood indicates anonymity
:rtype: bool
"""
return self.likelihood <= 3e-5 or self.longest_zero_run >= 384
Loading
Loading