pyforgeai-engine 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. pyforgeai_engine-1.0.0/LICENSE +21 -0
  2. pyforgeai_engine-1.0.0/PKG-INFO +200 -0
  3. pyforgeai_engine-1.0.0/README.md +168 -0
  4. pyforgeai_engine-1.0.0/pyproject.toml +60 -0
  5. pyforgeai_engine-1.0.0/setup.cfg +4 -0
  6. pyforgeai_engine-1.0.0/src/pyforgeai/AI_Controller.py +156 -0
  7. pyforgeai_engine-1.0.0/src/pyforgeai/AI_Factory.py +176 -0
  8. pyforgeai_engine-1.0.0/src/pyforgeai/Adapters/Mock_Adapter.py +31 -0
  9. pyforgeai_engine-1.0.0/src/pyforgeai/Adapters/PyTorch_Adapter.py +44 -0
  10. pyforgeai_engine-1.0.0/src/pyforgeai/Adapters/TensorFlow_Adapter.py +46 -0
  11. pyforgeai_engine-1.0.0/src/pyforgeai/Adapters/__init__.py +28 -0
  12. pyforgeai_engine-1.0.0/src/pyforgeai/Environments/Game_Bridge_Env.py +117 -0
  13. pyforgeai_engine-1.0.0/src/pyforgeai/Environments/Target_Seek_Env.py +69 -0
  14. pyforgeai_engine-1.0.0/src/pyforgeai/Environments/__init__.py +8 -0
  15. pyforgeai_engine-1.0.0/src/pyforgeai/Interfaces/IAIModel.py +60 -0
  16. pyforgeai_engine-1.0.0/src/pyforgeai/Interfaces/IEnvironment.py +48 -0
  17. pyforgeai_engine-1.0.0/src/pyforgeai/Interfaces/ITrainer.py +46 -0
  18. pyforgeai_engine-1.0.0/src/pyforgeai/Interfaces/__init__.py +12 -0
  19. pyforgeai_engine-1.0.0/src/pyforgeai/Models/Model_Builder.py +162 -0
  20. pyforgeai_engine-1.0.0/src/pyforgeai/Models/Neural_Network_Pytorch.py +72 -0
  21. pyforgeai_engine-1.0.0/src/pyforgeai/Models/Neural_Network_Tensorflow.py +91 -0
  22. pyforgeai_engine-1.0.0/src/pyforgeai/Models/__init__.py +28 -0
  23. pyforgeai_engine-1.0.0/src/pyforgeai/Serialization/Model_Serializer.py +307 -0
  24. pyforgeai_engine-1.0.0/src/pyforgeai/Serialization/__init__.py +21 -0
  25. pyforgeai_engine-1.0.0/src/pyforgeai/Trainers/Genetic_Algorithm.py +417 -0
  26. pyforgeai_engine-1.0.0/src/pyforgeai/Trainers/Q_Learning.py +413 -0
  27. pyforgeai_engine-1.0.0/src/pyforgeai/Trainers/Training_Callbacks.py +97 -0
  28. pyforgeai_engine-1.0.0/src/pyforgeai/Trainers/__init__.py +53 -0
  29. pyforgeai_engine-1.0.0/src/pyforgeai/__init__.py +109 -0
  30. pyforgeai_engine-1.0.0/src/pyforgeai_engine.egg-info/PKG-INFO +200 -0
  31. pyforgeai_engine-1.0.0/src/pyforgeai_engine.egg-info/SOURCES.txt +37 -0
  32. pyforgeai_engine-1.0.0/src/pyforgeai_engine.egg-info/dependency_links.txt +1 -0
  33. pyforgeai_engine-1.0.0/src/pyforgeai_engine.egg-info/requires.txt +8 -0
  34. pyforgeai_engine-1.0.0/src/pyforgeai_engine.egg-info/top_level.txt +1 -0
  35. pyforgeai_engine-1.0.0/tests/test_factory_and_envs.py +85 -0
  36. pyforgeai_engine-1.0.0/tests/test_genetic_trainer.py +107 -0
  37. pyforgeai_engine-1.0.0/tests/test_models_and_adapters.py +117 -0
  38. pyforgeai_engine-1.0.0/tests/test_qlearning_trainer.py +98 -0
  39. pyforgeai_engine-1.0.0/tests/test_serialization.py +71 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Drakonosinc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,200 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyforgeai-engine
3
+ Version: 1.0.0
4
+ Summary: A modular, multi-backend game AI training and inference library featuring Neuroevolution (Genetic Algorithms) and Deep Q-Learning (DQN) for Pygame and Python simulations.
5
+ Author: Drakonosinc
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Drakonosinc/PyForgeAI
8
+ Project-URL: Repository, https://github.com/Drakonosinc/PyForgeAI
9
+ Project-URL: Documentation, https://deepwiki.com/Drakonosinc/PyForgeAI
10
+ Keywords: ai,gamedev,pygame,pytorch,tensorflow,reinforcement-learning,q-learning,dqn,genetic-algorithm,neuroevolution,neural-network
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Games/Entertainment
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: numpy>=1.24.0
26
+ Requires-Dist: torch>=2.0.0
27
+ Provides-Extra: tensorflow
28
+ Requires-Dist: tensorflow>=2.12.0; extra == "tensorflow"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # PyForgeAI
34
+
35
+ [![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-4B32C3?logo=read-the-docs&logoColor=white)](https://deepwiki.com/Drakonosinc/PyForgeAI)
36
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
37
+ [![PyTorch 2.0+](https://img.shields.io/badge/PyTorch-2.0%2B-EE4C2C.svg?logo=pytorch&logoColor=white)](https://pytorch.org/)
38
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
39
+
40
+ **PyForgeAI** is a modular, multi-backend game AI training and inference library built for **Pygame** and real-time Python simulations. Designed around the `AIFactory`, `ITrainer`, and `IAIModel` patterns, it unifies **Neuroevolution (Genetic Algorithms)** and **Deep Q-Learning (Double-DQN)** into a clean, zero-boilerplate package with automatic HUD activation tracking and backward-compatible checkpoint serialization.
41
+
42
+ ---
43
+
44
+ ## Features
45
+
46
+ - **Unified Training Algorithms (`Trainers`)**:
47
+ - **`GeneticTrainer` (Neuroevolution)**: Elitism, multi-trial fitness averaging, uniform tensor crossover, **adaptive mutation scaling** on fitness stagnation, and periodic **random diversity injection**.
48
+ - **`QLearningTrainer` & `DQNAgent` (Deep Reinforcement Learning)**: Experience `ReplayMemory`, **Double-DQN** action evaluation, Huber/MSE loss, gradient clipping, and epsilon-greedy exploration decay.
49
+ - **Multi-Backend Neural Networks & Adapters (`Models` & `Adapters`)**:
50
+ - Dynamic multi-layer perceptrons (`SimpleNN_Pytorch` & `SimpleNN_Tensorflow`) with configurable `hidden_sizes` and activation functions (`relu`, `tanh`, `leaky_relu`, `elu`).
51
+ - Built-in normalized layer-1 activation capture (`model.activations` in `[0, 1]`) for real-time HUD neural network rendering, with a headless fast-mode toggle (`record_activations=False`).
52
+ - `PyTorchAdapter`, `TensorFlowAdapter`, and `MockAdapter` implementing the unified `IAIModel` contract (`predict`, `predict_action`, `predict_probabilities`, `get_weights`, `set_weights`).
53
+ - **Flexible Environment Integration (`Environments`)**:
54
+ - Works seamlessly with step-by-step Gym-like environments (`IEnvironment`), pure fitness callables (`fn(model) -> float`), or legacy Pygame loops (`game.run_with_model()` via `GameFitnessBridge`).
55
+ - **Smart Checkpoint Serialization (`Serialization`)**:
56
+ - Automatic architecture metadata persistence and legacy layer remapping (`fc1`/`fc2` $\rightarrow$ `hidden_layers.*`) via `save_model`, `load_model`, and configuration-driven `AILoader`.
57
+ - **Training Lifecycle Callbacks**:
58
+ - Built-in `EarlyStoppingCallback`, `CheckpointCallback`, and `HistoryCallback`.
59
+
60
+ ---
61
+
62
+ ## Architecture
63
+
64
+ ```mermaid
65
+ flowchart TD
66
+ Factory["AIFactory"] --> Models["Models (SimpleNN_Pytorch / SimpleNN_Tensorflow)"]
67
+ Factory --> Adapters["Adapters (PyTorchAdapter / TensorFlowAdapter / MockAdapter)"]
68
+ Factory --> Trainers["Trainers (GeneticTrainer / QLearningTrainer)"]
69
+ Factory --> Controller["AIController (Runtime Inference & Episodic DQN State)"]
70
+
71
+ Trainers --> Env["Environments (IEnvironment / IFitnessEnvironment / GameFitnessBridge)"]
72
+ Trainers --> Callbacks["Callbacks (EarlyStopping / Checkpoint / History)"]
73
+ Controller --> Adapters
74
+ Adapters --> Serializer["Serialization (save_model / load_model / AILoader)"]
75
+ ```
76
+
77
+ ---
78
+
79
+ ## Installation
80
+
81
+ ### From PyPI (once published)
82
+ ```bash
83
+ pip install pyforgeai-engine
84
+ ```
85
+
86
+ ### Local Editable Install (for development or local game projects)
87
+ ```bash
88
+ pip install -e .
89
+ ```
90
+
91
+ Optional TensorFlow backend support:
92
+ ```bash
93
+ pip install -e ".[tensorflow]"
94
+ ```
95
+
96
+ ---
97
+
98
+ ## Quickstart
99
+
100
+ ### 1. Neuroevolution (`GeneticTrainer`)
101
+
102
+ ```python
103
+ from pyforgeai import AIFactory, EarlyStoppingCallback, TargetSeekEnvironment, save_model
104
+
105
+ env = TargetSeekEnvironment(max_steps=80, seed=42)
106
+
107
+ factory = AIFactory({
108
+ "type_model": "Pytorch",
109
+ "input_size": env.state_size,
110
+ "output_size": env.action_size,
111
+ "hidden_sizes": [16, 16],
112
+ })
113
+
114
+ trainer = factory.create_GeneticTrainer(
115
+ generations=50,
116
+ population_size=20,
117
+ elitism=2,
118
+ num_trials=3,
119
+ adaptive_mutation=True,
120
+ diversity_interval=10,
121
+ callbacks=[EarlyStoppingCallback(patience=10)],
122
+ )
123
+
124
+ result = trainer.train_with_result(env)
125
+ save_model(result.best_model, "AI/best_genetic_model.pth")
126
+ ```
127
+
128
+ ### 2. Deep Q-Learning (`QLearningTrainer` / `DQNAgent`)
129
+
130
+ ```python
131
+ from pyforgeai import AIFactory, TargetSeekEnvironment
132
+
133
+ env = TargetSeekEnvironment(max_steps=80)
134
+ factory = AIFactory({
135
+ "input_size": env.state_size,
136
+ "output_size": env.action_size,
137
+ "hidden_sizes": [32, 32],
138
+ })
139
+
140
+ dqn_trainer = factory.create_QLearningTrainer(
141
+ episodes=200,
142
+ lr=1e-3,
143
+ gamma=0.99,
144
+ epsilon_start=1.0,
145
+ epsilon_end=0.02,
146
+ epsilon_decay=0.995,
147
+ double_dqn=True,
148
+ save_path="AI/best_dqn_model.pth",
149
+ )
150
+
151
+ result = dqn_trainer.train_environment_with_result(env)
152
+ ```
153
+
154
+ ### 3. Runtime Inference in Pygame (`AIController`)
155
+
156
+ ```python
157
+ from pyforgeai import AIController, load_model
158
+
159
+ model = load_model("AI/best_genetic_model.pth", "Pytorch")
160
+
161
+ controller = AIController(
162
+ state_provider=lambda: game.get_observation_array(),
163
+ action_dispatcher=lambda action_idx: game.apply_ai_action(action_idx),
164
+ )
165
+ controller.set_runtime_model(model)
166
+
167
+ # Inside your Pygame loop:
168
+ chosen_action = controller.select_action(deterministic=True)
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Running the Showcase Demo & Unit Tests
174
+
175
+ Run the standalone training and inference showcase:
176
+ ```bash
177
+ python demo_ai_training.py
178
+ ```
179
+
180
+ Run the automated test suite:
181
+ ```bash
182
+ python -m unittest discover -s tests -v
183
+ ```
184
+
185
+ Build `.whl` and `.tar.gz` distributions for PyPI:
186
+ ```bash
187
+ pip install build twine
188
+ python -m build
189
+ twine upload dist/*
190
+ ```
191
+
192
+ ---
193
+
194
+ ## License
195
+
196
+ This project is licensed under the [MIT License](LICENSE).
197
+
198
+ ## Author
199
+
200
+ Developed by [Drakonosinc](https://github.com/Drakonosinc)
@@ -0,0 +1,168 @@
1
+ # PyForgeAI
2
+
3
+ [![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-4B32C3?logo=read-the-docs&logoColor=white)](https://deepwiki.com/Drakonosinc/PyForgeAI)
4
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
5
+ [![PyTorch 2.0+](https://img.shields.io/badge/PyTorch-2.0%2B-EE4C2C.svg?logo=pytorch&logoColor=white)](https://pytorch.org/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
7
+
8
+ **PyForgeAI** is a modular, multi-backend game AI training and inference library built for **Pygame** and real-time Python simulations. Designed around the `AIFactory`, `ITrainer`, and `IAIModel` patterns, it unifies **Neuroevolution (Genetic Algorithms)** and **Deep Q-Learning (Double-DQN)** into a clean, zero-boilerplate package with automatic HUD activation tracking and backward-compatible checkpoint serialization.
9
+
10
+ ---
11
+
12
+ ## Features
13
+
14
+ - **Unified Training Algorithms (`Trainers`)**:
15
+ - **`GeneticTrainer` (Neuroevolution)**: Elitism, multi-trial fitness averaging, uniform tensor crossover, **adaptive mutation scaling** on fitness stagnation, and periodic **random diversity injection**.
16
+ - **`QLearningTrainer` & `DQNAgent` (Deep Reinforcement Learning)**: Experience `ReplayMemory`, **Double-DQN** action evaluation, Huber/MSE loss, gradient clipping, and epsilon-greedy exploration decay.
17
+ - **Multi-Backend Neural Networks & Adapters (`Models` & `Adapters`)**:
18
+ - Dynamic multi-layer perceptrons (`SimpleNN_Pytorch` & `SimpleNN_Tensorflow`) with configurable `hidden_sizes` and activation functions (`relu`, `tanh`, `leaky_relu`, `elu`).
19
+ - Built-in normalized layer-1 activation capture (`model.activations` in `[0, 1]`) for real-time HUD neural network rendering, with a headless fast-mode toggle (`record_activations=False`).
20
+ - `PyTorchAdapter`, `TensorFlowAdapter`, and `MockAdapter` implementing the unified `IAIModel` contract (`predict`, `predict_action`, `predict_probabilities`, `get_weights`, `set_weights`).
21
+ - **Flexible Environment Integration (`Environments`)**:
22
+ - Works seamlessly with step-by-step Gym-like environments (`IEnvironment`), pure fitness callables (`fn(model) -> float`), or legacy Pygame loops (`game.run_with_model()` via `GameFitnessBridge`).
23
+ - **Smart Checkpoint Serialization (`Serialization`)**:
24
+ - Automatic architecture metadata persistence and legacy layer remapping (`fc1`/`fc2` $\rightarrow$ `hidden_layers.*`) via `save_model`, `load_model`, and configuration-driven `AILoader`.
25
+ - **Training Lifecycle Callbacks**:
26
+ - Built-in `EarlyStoppingCallback`, `CheckpointCallback`, and `HistoryCallback`.
27
+
28
+ ---
29
+
30
+ ## Architecture
31
+
32
+ ```mermaid
33
+ flowchart TD
34
+ Factory["AIFactory"] --> Models["Models (SimpleNN_Pytorch / SimpleNN_Tensorflow)"]
35
+ Factory --> Adapters["Adapters (PyTorchAdapter / TensorFlowAdapter / MockAdapter)"]
36
+ Factory --> Trainers["Trainers (GeneticTrainer / QLearningTrainer)"]
37
+ Factory --> Controller["AIController (Runtime Inference & Episodic DQN State)"]
38
+
39
+ Trainers --> Env["Environments (IEnvironment / IFitnessEnvironment / GameFitnessBridge)"]
40
+ Trainers --> Callbacks["Callbacks (EarlyStopping / Checkpoint / History)"]
41
+ Controller --> Adapters
42
+ Adapters --> Serializer["Serialization (save_model / load_model / AILoader)"]
43
+ ```
44
+
45
+ ---
46
+
47
+ ## Installation
48
+
49
+ ### From PyPI (once published)
50
+ ```bash
51
+ pip install pyforgeai-engine
52
+ ```
53
+
54
+ ### Local Editable Install (for development or local game projects)
55
+ ```bash
56
+ pip install -e .
57
+ ```
58
+
59
+ Optional TensorFlow backend support:
60
+ ```bash
61
+ pip install -e ".[tensorflow]"
62
+ ```
63
+
64
+ ---
65
+
66
+ ## Quickstart
67
+
68
+ ### 1. Neuroevolution (`GeneticTrainer`)
69
+
70
+ ```python
71
+ from pyforgeai import AIFactory, EarlyStoppingCallback, TargetSeekEnvironment, save_model
72
+
73
+ env = TargetSeekEnvironment(max_steps=80, seed=42)
74
+
75
+ factory = AIFactory({
76
+ "type_model": "Pytorch",
77
+ "input_size": env.state_size,
78
+ "output_size": env.action_size,
79
+ "hidden_sizes": [16, 16],
80
+ })
81
+
82
+ trainer = factory.create_GeneticTrainer(
83
+ generations=50,
84
+ population_size=20,
85
+ elitism=2,
86
+ num_trials=3,
87
+ adaptive_mutation=True,
88
+ diversity_interval=10,
89
+ callbacks=[EarlyStoppingCallback(patience=10)],
90
+ )
91
+
92
+ result = trainer.train_with_result(env)
93
+ save_model(result.best_model, "AI/best_genetic_model.pth")
94
+ ```
95
+
96
+ ### 2. Deep Q-Learning (`QLearningTrainer` / `DQNAgent`)
97
+
98
+ ```python
99
+ from pyforgeai import AIFactory, TargetSeekEnvironment
100
+
101
+ env = TargetSeekEnvironment(max_steps=80)
102
+ factory = AIFactory({
103
+ "input_size": env.state_size,
104
+ "output_size": env.action_size,
105
+ "hidden_sizes": [32, 32],
106
+ })
107
+
108
+ dqn_trainer = factory.create_QLearningTrainer(
109
+ episodes=200,
110
+ lr=1e-3,
111
+ gamma=0.99,
112
+ epsilon_start=1.0,
113
+ epsilon_end=0.02,
114
+ epsilon_decay=0.995,
115
+ double_dqn=True,
116
+ save_path="AI/best_dqn_model.pth",
117
+ )
118
+
119
+ result = dqn_trainer.train_environment_with_result(env)
120
+ ```
121
+
122
+ ### 3. Runtime Inference in Pygame (`AIController`)
123
+
124
+ ```python
125
+ from pyforgeai import AIController, load_model
126
+
127
+ model = load_model("AI/best_genetic_model.pth", "Pytorch")
128
+
129
+ controller = AIController(
130
+ state_provider=lambda: game.get_observation_array(),
131
+ action_dispatcher=lambda action_idx: game.apply_ai_action(action_idx),
132
+ )
133
+ controller.set_runtime_model(model)
134
+
135
+ # Inside your Pygame loop:
136
+ chosen_action = controller.select_action(deterministic=True)
137
+ ```
138
+
139
+ ---
140
+
141
+ ## Running the Showcase Demo & Unit Tests
142
+
143
+ Run the standalone training and inference showcase:
144
+ ```bash
145
+ python demo_ai_training.py
146
+ ```
147
+
148
+ Run the automated test suite:
149
+ ```bash
150
+ python -m unittest discover -s tests -v
151
+ ```
152
+
153
+ Build `.whl` and `.tar.gz` distributions for PyPI:
154
+ ```bash
155
+ pip install build twine
156
+ python -m build
157
+ twine upload dist/*
158
+ ```
159
+
160
+ ---
161
+
162
+ ## License
163
+
164
+ This project is licensed under the [MIT License](LICENSE).
165
+
166
+ ## Author
167
+
168
+ Developed by [Drakonosinc](https://github.com/Drakonosinc)
@@ -0,0 +1,60 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pyforgeai-engine"
7
+ version = "1.0.0"
8
+ description = "A modular, multi-backend game AI training and inference library featuring Neuroevolution (Genetic Algorithms) and Deep Q-Learning (DQN) for Pygame and Python simulations."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "Drakonosinc" }
14
+ ]
15
+ keywords = [
16
+ "ai",
17
+ "gamedev",
18
+ "pygame",
19
+ "pytorch",
20
+ "tensorflow",
21
+ "reinforcement-learning",
22
+ "q-learning",
23
+ "dqn",
24
+ "genetic-algorithm",
25
+ "neuroevolution",
26
+ "neural-network",
27
+ ]
28
+ classifiers = [
29
+ "Development Status :: 5 - Production/Stable",
30
+ "Intended Audience :: Developers",
31
+ "Intended Audience :: Science/Research",
32
+ "License :: OSI Approved :: MIT License",
33
+ "Operating System :: OS Independent",
34
+ "Programming Language :: Python :: 3",
35
+ "Programming Language :: Python :: 3.10",
36
+ "Programming Language :: Python :: 3.11",
37
+ "Programming Language :: Python :: 3.12",
38
+ "Topic :: Games/Entertainment",
39
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
40
+ ]
41
+ dependencies = [
42
+ "numpy>=1.24.0",
43
+ "torch>=2.0.0",
44
+ ]
45
+
46
+ [project.optional-dependencies]
47
+ tensorflow = [
48
+ "tensorflow>=2.12.0",
49
+ ]
50
+ dev = [
51
+ "pytest>=7.0.0",
52
+ ]
53
+
54
+ [project.urls]
55
+ Homepage = "https://github.com/Drakonosinc/PyForgeAI"
56
+ Repository = "https://github.com/Drakonosinc/PyForgeAI"
57
+ Documentation = "https://deepwiki.com/Drakonosinc/PyForgeAI"
58
+
59
+ [tool.setuptools.packages.find]
60
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,156 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Callable
4
+ import numpy as np
5
+
6
+ from .Adapters import MockAdapter, PyTorchAdapter, TensorFlowAdapter, wrap_model
7
+ from .Interfaces.IAIModel import IAIModel
8
+ from .Serialization.Model_Serializer import load_model, save_model
9
+ from .Trainers.Q_Learning import QLearningTrainer, get_active_qlearning_trainer
10
+
11
+
12
+ class AIController:
13
+ """Reusable runtime AI controller managing inference adapters and episodic Q-Learning state transitions."""
14
+
15
+ def __init__(
16
+ self,
17
+ state_provider: Callable[[], np.ndarray] | None = None,
18
+ action_dispatcher: Callable[[int | np.ndarray], None] | None = None,
19
+ default_backend: str = "Pytorch",
20
+ output_size: int = 2,
21
+ ) -> None:
22
+ self.state_provider = state_provider
23
+ self.action_dispatcher = action_dispatcher
24
+ self.default_backend = default_backend
25
+ self.output_size = int(output_size)
26
+
27
+ self.model_adapter: IAIModel | None = None
28
+ self.prev_state: np.ndarray | None = None
29
+ self.prev_action: int | None = None
30
+ self.prev_reward: float = 0.0
31
+
32
+ def set_model(self, model_adapter: IAIModel) -> None:
33
+ self.model_adapter = model_adapter
34
+
35
+ def clear_model(self) -> None:
36
+ self.model_adapter = None
37
+
38
+ def set_runtime_model(self, model: Any, type_model: str | None = None) -> IAIModel | None:
39
+ """Wrap and bind a raw PyTorch/TensorFlow model or IAIModel adapter only when it changes."""
40
+ if model is None:
41
+ return None
42
+ if isinstance(model, IAIModel):
43
+ self.model_adapter = model
44
+ return self.model_adapter
45
+
46
+ current_internal = self.model_adapter.get_internal_model() if self.model_adapter is not None else None
47
+ if current_internal is model:
48
+ return self.model_adapter
49
+
50
+ backend = (type_model or self.default_backend).strip().capitalize()
51
+ if backend in ("Pytorch", "Torch"):
52
+ self.model_adapter = PyTorchAdapter(model)
53
+ elif backend in ("Tensorflow", "Tf", "Keras"):
54
+ self.model_adapter = TensorFlowAdapter(model)
55
+ else:
56
+ self.model_adapter = wrap_model(model, output_size=self.output_size)
57
+ return self.model_adapter
58
+
59
+ def get_state(self) -> np.ndarray:
60
+ if self.state_provider is not None:
61
+ return np.asarray(self.state_provider(), dtype=np.float32)
62
+ if self.prev_state is not None:
63
+ return self.prev_state.copy()
64
+ raise RuntimeError("No state_provider configured and no previous state available.")
65
+
66
+ @staticmethod
67
+ def softmax(x: np.ndarray | list[float]) -> np.ndarray:
68
+ arr = np.asarray(x, dtype=np.float32).flatten()
69
+ exp_x = np.exp(arr - np.max(arr))
70
+ total = np.sum(exp_x)
71
+ return exp_x / total if total != 0.0 else np.full_like(arr, 1.0 / max(1, len(arr)))
72
+
73
+ def predict(self, state: np.ndarray | list[float] | None = None) -> np.ndarray | None:
74
+ if self.model_adapter is None:
75
+ return None
76
+ obs = np.asarray(state, dtype=np.float32) if state is not None else self.get_state()
77
+ return self.model_adapter.predict(obs)
78
+
79
+ def select_action(self, state: np.ndarray | list[float] | None = None, deterministic: bool = True) -> int | None:
80
+ if self.model_adapter is None:
81
+ return None
82
+ obs = np.asarray(state, dtype=np.float32) if state is not None else self.get_state()
83
+ action = self.model_adapter.predict_action(obs, deterministic=deterministic)
84
+ if self.action_dispatcher is not None:
85
+ self.action_dispatcher(action)
86
+ return action
87
+
88
+ def step_qlearning(
89
+ self,
90
+ current_state: np.ndarray | list[float],
91
+ current_reward: float,
92
+ done: bool = False,
93
+ trainer: QLearningTrainer | None = None,
94
+ use_reward_delta: bool = True,
95
+ ) -> int | None:
96
+ """Process one Q-Learning frame: record transition from previous frame, optimize, and return next action."""
97
+ active_trainer = trainer or get_active_qlearning_trainer()
98
+ if active_trainer is None:
99
+ return None
100
+
101
+ curr_state_arr = np.asarray(current_state, dtype=np.float32)
102
+ if self.prev_state is not None and self.prev_action is not None:
103
+ step_reward = (float(current_reward) - self.prev_reward) if use_reward_delta else float(current_reward)
104
+ active_trainer.store_experience(
105
+ self.prev_state,
106
+ self.prev_action,
107
+ step_reward,
108
+ curr_state_arr,
109
+ bool(done),
110
+ )
111
+
112
+ action = active_trainer.get_action(curr_state_arr)
113
+ if self.action_dispatcher is not None:
114
+ self.action_dispatcher(action)
115
+
116
+ self.prev_state = curr_state_arr.copy()
117
+ self.prev_action = action
118
+ self.prev_reward = float(current_reward)
119
+ if done:
120
+ self.reset_qlearning_state()
121
+ return action
122
+
123
+ def reset_qlearning_state(self) -> None:
124
+ self.prev_state = None
125
+ self.prev_action = None
126
+ self.prev_reward = 0.0
127
+
128
+ def manual_save_model(self, path: str) -> None:
129
+ if self.model_adapter is not None:
130
+ internal = self.model_adapter.get_internal_model()
131
+ if internal is not None:
132
+ save_model(internal, path)
133
+ else:
134
+ self.model_adapter.save(path)
135
+
136
+ def manual_load_model(
137
+ self,
138
+ path: str,
139
+ input_size: int | None = None,
140
+ output_size: int | None = None,
141
+ hidden_sizes: list[int] | None = None,
142
+ ) -> IAIModel | None:
143
+ loaded = load_model(
144
+ path=path,
145
+ model_or_type_model=self.default_backend,
146
+ input_size=input_size,
147
+ output_size=output_size or self.output_size,
148
+ hidden_sizes=hidden_sizes,
149
+ )
150
+ if loaded is not None:
151
+ return self.set_runtime_model(loaded, type_model=self.default_backend)
152
+ return None
153
+
154
+
155
+ # Alias for backward compatibility with Pong_Game / Snake_Game
156
+ AIHandler = AIController