generate_docs.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. #ident "@(#)$Format:LocalFoodAI:generate_docs.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  2. # $Id$
  3. # $Author$
  4. # $log$
  5. import os
  6. #ident "@(#)$Format:LocalFoodAI:generate_docs.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  7. import subprocess
  8. docs_dir = "docs"
  9. os.makedirs(docs_dir, exist_ok=True)
  10. docs = {
  11. "URL_Formats.md": """# $Id$
  12. # Local Food AI - Network Connection URL Directory
  13. This runbook catalogs the specific network formats and port endpoints required to access the application and monitoring servers across different loopback, hostname, and address protocols.
  14. ## 1. Localhost Format (Loopback)
  15. - **Streamlit Web Application UI**: `http://localhost:100` *(via Nginx)* or `http://localhost:8522` *(direct)*
  16. - **Zabbix Web UI Console**: `http://localhost:8101`
  17. - **Airflow Webserver DAG UI**: `http://localhost:8102`
  18. - **Ollama AI Local Engine**: `http://localhost:11434`
  19. - **SearXNG Meta-Search API**: `http://localhost:8105`
  20. - **MySQL Database Server**: `localhost:3326` *(direct SQL connection)*
  21. ## 2. Hostname Format (assuming Hostname is `XYZZYX`)
  22. - **Streamlit Web Application UI**: `http://XYZZYX:100` or `http://XYZZYX:8522`
  23. - **Zabbix Web UI Console**: `http://XYZZYX:8101`
  24. - **Airflow Webserver DAG UI**: `http://XYZZYX:8102`
  25. - **Ollama AI Local Engine**: `http://XYZZYX:11434`
  26. - **SearXNG Meta-Search API**: `http://XYZZYX:8105`
  27. - **MySQL Database Server**: `XYZZYX:3326`
  28. ## 3. IPv4 Format (assuming Local Host IP is `192.168.1.50`)
  29. - **Streamlit Web Application UI**: `http://192.168.1.50:100` or `http://192.168.1.50:8522` *(loopback: `http://127.0.0.1:100`)*
  30. - **Zabbix Web UI Console**: `http://192.168.1.50:8101` *(loopback: `http://127.0.0.1:8101`)*
  31. - **Airflow Webserver DAG UI**: `http://192.168.1.50:8102` *(loopback: `http://127.0.0.1:8102`)*
  32. - **Ollama AI Local Engine**: `http://192.168.1.50:11434` *(loopback: `http://127.0.0.1:11434`)*
  33. - **SearXNG Meta-Search API**: `http://192.168.1.50:8105` *(loopback: `http://127.0.0.1:8105`)*
  34. - **MySQL Database Server**: `192.168.1.50:3326` *(loopback: `127.0.0.1:3326`)*
  35. ## 4. IPv6 Format (using loopback `[::1]` or link-local address)
  36. - **Streamlit Web Application UI**: `http://[::1]:100` or `http://[::1]:8522`
  37. - **Zabbix Web UI Console**: `http://[::1]:8101`
  38. - **Airflow Webserver DAG UI**: `http://[::1]:8102`
  39. - **Ollama AI Local Engine**: `http://[::1]:11434`
  40. - **SearXNG Meta-Search API**: `http://[::1]:8105`
  41. - **MySQL Database Server**: `[::1]:3326`
  42. """,
  43. "Final_Report.md": """# $Id$
  44. # Final Project Report (Living Document)
  45. ## What Has Been Done
  46. 1. **Core Architecture**: Deployed a resilient 8-container local fallback Docker Compose stack (MySQL, Streamlit UI, local Ollama LLM, anonymous SearXNG search, secure Nginx proxy, and local Zabbix Server/Web/Agent observability suite).
  47. 2. **Database Optimization**: Successfully loaded OpenFoodFacts records and utilized advanced vertical partitioning and FULLTEXT indices.
  48. 3. **Clinical Subquery Strategy**: Refactored the core Pandas/SQL query pipeline to use subquery limiting, resolving Cartesian join explosions and reducing query latency to ~0.04s.
  49. 4. **Monitoring & Security**: Nginx securely proxies traffic on Port 80. Zabbix actively monitors proxy and server health, dynamically handling SNMP/alert loops in local/offline fallback mode.
  50. 5. **Git Versioning**: Implemented Git `.gitattributes` to push `$Id$` tracking directly into the Python Application UI.
  51. ## What Needs To Be Done (Day 2 Operations)
  52. 1. **SSL/TLS Certificates**: The Nginx proxy is functional on HTTP port 80. Port 443 (HTTPS) must be configured with a Let's Encrypt certificate for true production encryption.
  53. 2. **User Acceptance Testing (UAT)**: Clinical dietitians should rigorously test the AI Chat constraints and Plate Builder to ensure edge cases are handled safely.
  54. 3. **Advanced Rate Limiting**: Limit the number of AI requests per user using a sliding window algorithm in `app.py`.
  55. ## What Is The Next Step
  56. - Execute the `data_sync.sh` cron job monthly.
  57. - Maintain the automated `backup_db.sh` 7-day retention cycle.
  58. - Begin the hand-off to the operational team for Phase 2 feature requests.
  59. """,
  60. "Backup_Procedure.md": """# $Id$
  61. # Database Backup and Restore Procedure
  62. ## 1. Overview & Policy
  63. To guarantee clinical records integrity and high availability, Local Food AI enforces a strict backup schedule.
  64. - **Scope**: Includes MySQL schemas (`food_db`), user profiles (`app_auth`), and configuration states.
  65. - **Retention Plan**: Automated daily backups with a strict 7-day rolling window purge.
  66. - **Storage Location**: Stored securely inside the persistent `/backups` directory on the host server.
  67. ---
  68. ## 2. Automated Daily Backups
  69. The automated backup mechanism runs via a host cron job pointing to `backup_db.sh`.
  70. - The script dynamically detects the active MySQL container name (`food-mysql-1` or `food_project-mysql-1`).
  71. - It executes `mysqldump` directly inside the container without exposing root passwords to shell logs.
  72. - Outputs are compressed via `gzip` and timestamped: `food_db_YYYYMMDD_HHMM.sql.gz`.
  73. ### Cron Configuration Example:
  74. To run the backup daily at 02:00 AM, add the following to `/etc/crontab`:
  75. ```bash
  76. 0 2 * * * root /bin/bash /c/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/backup_db.sh >> /var/log/backup_db.log 2>&1
  77. ```
  78. ---
  79. ## 3. Manual Backup Execution
  80. If a system migration or major upgrade is scheduled, perform a manual dump using the following command:
  81. ```bash
  82. # 1. Navigate to the project directory
  83. cd /c/Users/lanfr144/Documents/DOPRO1/Antigravity/Food
  84. # 2. Run the backup wrapper
  85. bash backup_db.sh
  86. ```
  87. Verify the output exists inside the backups folder:
  88. ```bash
  89. ls -lh backups/
  90. ```
  91. ---
  92. ## 4. Step-by-Step Restore Procedure
  93. In the event of database corruption or hardware failure, follow these exact steps to restore the database.
  94. ### Step 4.1: Identify the Target Backup File
  95. List available files and pick the desired timestamp:
  96. ```bash
  97. ls -la backups/
  98. # Example Target: backups/food_db_20260521_1100.sql.gz
  99. ```
  100. ### Step 4.2: Verify MySQL Container Health
  101. Ensure the MySQL service container is running and healthy:
  102. ```bash
  103. docker ps --filter name=mysql
  104. ```
  105. ### Step 4.3: Execute Restore Stream
  106. Decompress the backup on-the-fly and pipe it directly into the running MySQL container:
  107. ```bash
  108. # Adjust the container name ('food-mysql-1' or 'food_project-mysql-1') based on active deployment
  109. gunzip < backups/food_db_20260521_1100.sql.gz | docker exec -i food-mysql-1 mysql -u root -proot_pass food_db
  110. ```
  111. ### Step 4.4: Verify Restored Tables
  112. Log in to the database and query the core table to confirm the tables are intact and populated:
  113. ```bash
  114. docker exec -it food-mysql-1 mysql -u food_reader -preader_pass food_db -e "SELECT COUNT(*) FROM products_core;"
  115. ```
  116. Expected result: A count of OpenFoodFacts entries (typically > 10,000 records).
  117. ---
  118. ## 5. Verification & Health Check Loops
  119. Operators must verify the backup archive integrity weekly:
  120. 1. Copy the `.gz` backup to a local testing workspace.
  121. 2. Run `gzip -t backups/filename.sql.gz` to ensure the archive is not corrupted.
  122. 3. Test restoring to a local fallback container instance to verify data accessibility.
  123. """,
  124. "Data_Ingestion.md": """# $Id$
  125. # Data Ingestion Pipeline
  126. ## Overview
  127. The application utilizes `data_sync.sh` to update the OpenFoodFacts dataset.
  128. ## Online Mode
  129. Run `bash data_sync.sh --online`. The script will download the latest CSV directly from the official servers and trigger the ingestion pipeline.
  130. ## Offline Mode
  131. Drop a `en.openfoodfacts.org.products.csv` file into the `/data` folder and run `bash data_sync.sh`. The script detects the file and triggers the Docker ingestion container.
  132. """,
  133. "Installation_Guide.md": """# $Id$
  134. # Local Food AI - Detailed Installation and Deployment Guide
  135. This guide describes how to provision the host hypervisor, install Docker on Ubuntu, clone the repository, check out the correct branch, and launch the application.
  136. ## 1. WSL2 Ubuntu Instance Setup
  137. To create a dedicated WSL2 environment for the application, execute the following command in an Administrator PowerShell window:
  138. ```powershell
  139. wsl --install -d Ubuntu-22.04 --name Dopro1
  140. ```
  141. During initialization, configure the default Unix user and password as prompted:
  142. ```
  143. Create a default Unix user account: lanfr144
  144. New password:
  145. Retype new password:
  146. passwd: password updated successfully
  147. ```
  148. > [!WARNING]
  149. > **WSL Filesystem Mounts**: By default, launching WSL may place you in a Windows filesystem mount (e.g. `/mnt/d/...`). To prevent performance degradation and permission bugs, navigate to your WSL home directory immediately:
  150. ```bash
  151. cd ~
  152. ```
  153. ---
  154. ## 2. Docker & Docker Compose Installation inside WSL Ubuntu
  155. To install Docker directly inside your WSL Ubuntu instance (without Docker Desktop):
  156. ### Step 2.1: Clean Existing Docker Versions
  157. ```bash
  158. sudo apt remove -y docker.io docker-compose docker-compose-v2 docker-doc podman-docker containerd runc
  159. ```
  160. ### Step 2.2: Add Docker's Official GPG Key & Repository
  161. ```bash
  162. sudo apt update
  163. sudo apt install -y ca-certificates curl
  164. sudo install -m 0755 -d /etc/apt/keyrings
  165. sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
  166. sudo chmod a+r /etc/apt/keyrings/docker.asc
  167. sudo tee /etc/apt/sources.list.d/docker.sources <<EOF
  168. Types: deb
  169. URIs: https://download.docker.com/linux/ubuntu
  170. Suites: \$(. /etc/os-release && echo "\${UBUNTU_CODENAME:-\$VERSION_CODENAME}")
  171. Components: stable
  172. Architectures: \$(dpkg --print-architecture)
  173. Signed-By: /etc/apt/keyrings/docker.asc
  174. EOF
  175. ```
  176. ### Step 2.3: Install Docker Components
  177. ```bash
  178. sudo apt update
  179. sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  180. ```
  181. ### Step 2.4: Start and Enable Docker Daemon
  182. ```bash
  183. sudo systemctl start docker
  184. sudo systemctl enable docker
  185. ```
  186. ### Step 2.5: Add User to the Docker Group
  187. Ensure you can execute Docker commands without `sudo`:
  188. ```bash
  189. grep "^docker:" /etc/group || sudo addgroup docker
  190. sudo usermod -aG docker \$USER
  191. ```
  192. ### Step 2.6: Reboot the WSL Instance
  193. Execute the command below inside WSL to gracefully reboot the instance:
  194. ```bash
  195. cd /mnt/c/ && cmd.exe /c start "rebooting WSL" cmd /c "timeout 5 && wsl -d \$WSL_DISTRO_NAME" && wsl.exe --terminate \$WSL_DISTRO_NAME
  196. ```
  197. Upon reconnecting, verify Docker is running by starting the hello-world container:
  198. ```bash
  199. docker run hello-world
  200. ```
  201. ---
  202. ## 3. Network Configuration & Performance Tuning
  203. ### Step 3.1: Switch to Legacy IPTables
  204. Ubuntu 22.04 uses `nftables` by default. Switch to legacy iptables to ensure Docker network NAT rules match correctly:
  205. ```bash
  206. sudo update-alternatives --config iptables
  207. # Select option 1 (iptables-legacy)
  208. ```
  209. ### Step 3.2: Configure DNS Settings
  210. To ensure reliable package downloads and LLM registry calls:
  211. ```bash
  212. echo "1,\$ s/^/#/
  213. \$ a
  214. nameserver 1.1.1.1
  215. .
  216. w
  217. q" | sudo ed /etc/resolv.conf
  218. echo "\$ a
  219. # Added these 2 lines:
  220. [network]
  221. generateResolvConf = false
  222. .
  223. w
  224. q" | sudo ed /etc/wsl.conf
  225. ```
  226. ---
  227. ## 4. Repository Clones & Branch Governance
  228. There are two repositories configured for this project:
  229. - Production Repository: `https://git.btshub.lu/lanfr/LocalFoodAI_lanfr144.git`
  230. - GitHub Mirror (Clone): `https://github.com/lanfr144/LocalFoodAI_lanfr144`
  231. Clone the primary repository inside your home directory:
  232. ```bash
  233. git clone https://git.btshub.lu/lanfr/LocalFoodAI_lanfr144.git
  234. cd LocalFoodAI_lanfr144
  235. ```
  236. ### Step 4.1: List Available Branches
  237. Inspect both local and remote branches on the server:
  238. ```bash
  239. git branch -a
  240. ```
  241. *(Shows available branches like `remotes/origin/main` or `remotes/origin/dev`)*
  242. ### Step 4.2: Track and Check Out the Right Branch
  243. Select the main production branch and extract it:
  244. ```bash
  245. git checkout main
  246. ```
  247. *(If the repository uses a master branch, replace 'main' with 'master')*
  248. ### Step 4.3: Set Default Branch (Optional)
  249. To set the default tracking branch for your local copy:
  250. ```bash
  251. git remote set-head origin main
  252. ```
  253. ---
  254. ## 5. Launching the App
  255. Ensure the runbooks and sync scripts have executable permissions:
  256. ```bash
  257. chmod +x data_sync.sh backup_db.sh manage_services.sh scripts/manage_models.sh
  258. ```
  259. Follow the standard runbook to initialize credentials and launch services:
  260. ```bash
  261. # 1. Create a local .env file based on step 3 guidelines
  262. # 2. Run the service manager to spin up containers
  263. ./manage_services.sh start
  264. ```
  265. """,
  266. "User_Guide.md": """# $Id$
  267. Local Food AI - Clinician User Manual
  268. Welcome to the **Local Food AI** clinical dietitian explorer. This guide explains how to use the platform to search for products, build custom recipe plates, calculate cumulative nutritional statistics, and consult the privacy-safe AI assistant.
  269. ---
  270. ## 1. Accessing the Application
  271. To access the platform on your local network:
  272. 1. Open your web browser (Chrome, Firefox, or Safari).
  273. 2. Enter the host address provided by your IT administrator (e.g., `http://192.168.130.170:8502/` or `http://localhost:8502/`).
  274. 3. You will be greeted by the secure login screen.
  275. ---
  276. ## 2. Account Login & Security
  277. To protect patient information, the system requires credentials:
  278. * **Login**: Enter your standard clinician username and password.
  279. * **Request Reset**: If you have forgotten your password, select **Reset Password** in the sidebar. Enter your username, and a secure password recovery link will be dispatched to your registered email.
  280. * **Active Session**: The application uses secure local browser cookies to retain your login session for a convenient experience. Select **Logout** in the sidebar at any time to terminate your session.
  281. ---
  282. ## 3. Sidebar Features & Controls
  283. The left-hand sidebar houses several global settings:
  284. * **Network Status**: Visual indicator of whether you are in *Online/Server* mode or *Offline/Local Fallback* mode.
  285. * **LLM Engine Status**: Displays the active local AI model being queried (e.g., `llama3.2:3b`).
  286. * **Active User Info**: Shows the logged-in clinician profile.
  287. * **Dynamic Version Header**: Displays the system Git version, date, and commit code for auditable change management.
  288. ---
  289. ## 4. Feature Guides
  290. The application dashboard is split into three interactive workspace tabs:
  291. ### 4.1. Clinical Data Search Tab 🔍
  292. Use this tab to browse the local OpenFoodFacts food database.
  293. 1. **Keyword Input**: Type a product name, brand, or barcode (e.g., "whole wheat bread" or "unpasteurized cheese").
  294. 2. **Dynamic Results**: The database performs a rapid search, displaying the top 10 matched products.
  295. 3. **Nutritional Score**: Shows the Nutri-Score grade (A to E) and details (Proteins, Carbs, Fats, Energy in kcal) per 100g.
  296. 4. **Allergen Warnings**: Shows highlight flags if the product contains common allergens matching your client's needs.
  297. ### 4.2. My Plate Builder Tab 🍽️
  298. Build custom meals or recipe portions to calculate total client nutritional intake.
  299. 1. **Adding Items**: When browsing foods in the Search Tab, click **Add to Plate**.
  300. 2. **Specifying Portions**: Input the quantity using either decimal weights (in grams) or common volume descriptors (e.g., "1.5 cups", "2 tablespoons"). The converter translates volume to metric weight based on the product density.
  301. 3. **Cumulative Intake Table**: The tab renders a table summarizing individual macros and total energy.
  302. 4. **Visual Metrics**: Renders a dynamic bar chart comparing Carbs, Proteins, and Fats against recommended clinical intake thresholds.
  303. 5. **Editing the Plate**: Use the trash bin icon (🗑️) to instantly remove any item from the calculation.
  304. ### 4.3. Consultation Chat Tab 💬
  305. Consult the built-in clinical AI dietitian assistant for recipe validation, medical profile warnings, and meal plans.
  306. 1. **Client Profile Selection**: Select active dietary constraints (e.g., pregnancy, diabetes, kidney disease, vegetarian) in the dropdown.
  307. 2. **Asking Questions**: Type your prompt (e.g., "Is unpasteurized brie cheese safe for a pregnant client?" or "Design a low-sodium, high-protein menu").
  308. 3. **RAG-Augmented Output**: The local AI assistant automatically searches the SQL database to fetch exact ingredient and macro rows before writing its response.
  309. 4. **Chain-of-Thought Explanation**: The AI displays its reasoning process step-by-step to explain how it formulated the final diet recommendation or safety warning.
  310. ---
  311. ## 5. Privacy and Offline Support
  312. Because patient privacy is critical:
  313. * **No Cloud Overhead**: All search strings, chat prompts, and plate records are processed locally inside the host node.
  314. * **Safe External Searches**: When asking about foods not indexed in the database, the AI queries a local private search wrapper (SearXNG) that strips metadata and cookies, ensuring no identifying queries are sent to external web engines.
  315. """,
  316. "Technical_Document.md": """# $Id$
  317. Local Food AI - Capstone Technical Document
  318. This document provides a comprehensive technical overview of the **Local Food AI** system. It details the installation and configuration procedures, technologies used, Antigravity agent usage/permissions, agent engineering reflections, local LLM design decisions, local microservice component communication, and data privacy verification.
  319. ---
  320. ## 1. System Overview & Technologies Used
  321. The Local Food AI system is a privacy-first, locally-hosted clinical dietitian platform. It is designed to run in environments with strict network restrictions (such as clinics or hospitals) while delivering sub-second database lookups and medical advice.
  322. ### Technology Stack
  323. * **Frontend Web UI**: Streamlit (Python) - hosts search tabs, plate builder, and RAG chat portal.
  324. * **Database**: MySQL 8.0 - stores OpenFoodFacts records with dynamic vertical partitioning.
  325. * **Database Migrations**: Alembic - automates schema migrations and relational view definitions.
  326. * **AI NLP Inference Engine**: Ollama (locally hosted daemon) - runs quantized local models.
  327. * **Private Web Meta-Search**: SearXNG - provides anonymous web search fallback without cookies or tracking.
  328. * **Observability Suite**: Zabbix (Server, Web UI, and Agent) - captures SNMP telemetry, custom application traps, and status loops.
  329. * **Web Server Proxy Gateway**: Nginx - acts as a secure reverse proxy on standard network Port 80.
  330. * **Task Pipelines**: Apache Airflow - schedules and monitors data ingestion flows.
  331. ---
  332. ## 2. Dynamic Component Infrastructure Diagram
  333. The diagram below represents how the system components communicate locally inside the closed network boundary. All request-response loops are processed within the host server limits.
  334. ```mermaid
  335. flowchart TD
  336. subgraph "Client Layer"
  337. Browser["Clinician Browser"]
  338. end
  339. subgraph "Gateway & Application Nodes"
  340. Nginx["Nginx Reverse Proxy\n(Port 80)"]
  341. Streamlit["Streamlit Web App\n(Port 8502 / Docker Container)"]
  342. end
  343. subgraph "Intelligence & Search Nodes"
  344. Ollama["Ollama Daemon\n(Port 11434 / Docker Container)"]
  345. SearXNG["SearXNG Meta-Search\n(Port 8085 / Docker Container)"]
  346. end
  347. subgraph "Data Storage & Observability Nodes"
  348. MySQL["MySQL Database Server\n(Port 3306 / Docker Container)"]
  349. Zabbix["Zabbix Server & Agent\n(Ports 10051 & 10050)"]
  350. ZabbixWeb["Zabbix Web Dashboard\n(Port 8081)"]
  351. end
  352. %% Communication paths
  353. Browser -->|HTTP| Nginx
  354. Nginx -->|Reverse Proxy Pass| Streamlit
  355. Streamlit -->|EAV & FULLTEXT SQL queries| MySQL
  356. Streamlit -->|Local Chat Inference / RAG| Ollama
  357. Streamlit -->|Tool-Calling search queries| SearXNG
  358. Streamlit -->|SNMP Traps / Telemetry| Zabbix
  359. ZabbixWeb -->|Queries metrics| Zabbix
  360. ```
  361. ---
  362. ## 3. Installation & Configuration Guide
  363. To deploy the Local Food AI system, follow the sequential commands below:
  364. ### 3.1 Prerequisite Environment Setup
  365. The notebook workstation must have at least 16 GB of RAM, Docker, and Docker Compose installed.
  366. ### 3.2 Dynamic Double-Mode Configuration
  367. 1. **Host Environment File (`.env`)**:
  368. Configure database credentials, active network mode, and the target model name:
  369. ```ini
  370. NETWORK_MODE=server
  371. LLM_MODEL=llama3.2:3b
  372. MYSQL_ROOT_PASSWORD=your_db_password_here
  373. DB_READER_PASS=your_db_password_here
  374. DB_LOADER_PASS=your_db_password_here
  375. DB_APP_AUTH_PASS=your_db_password_here
  376. MYSQL_ZABBIX_PASSWORD=your_db_password_here
  377. SERVER_HOST=192.168.130.170
  378. SERVER_USER=francois
  379. SERVER_PASS=your_db_password_here
  380. ```
  381. 2. **Compose Topology Mappings**:
  382. The `app` container maps the host's `.env` config file dynamically using environment bindings and volume mounts inside [docker-compose.yml](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docker-compose.yml):
  383. ```yaml
  384. app:
  385. build:
  386. context: .
  387. dockerfile: docker/app/Dockerfile
  388. ports:
  389. - "8502:8501"
  390. environment:
  391. - DB_HOST=mysql
  392. - DB_USER=food_reader
  393. - DB_PASS=${DB_READER_PASS}
  394. - LLM_MODEL=${LLM_MODEL}
  395. volumes:
  396. - ./.env:/app/.env
  397. ```
  398. ### 3.3 Execution Commands
  399. * **Production Build & Launch**:
  400. ```bash
  401. docker compose up -d --build
  402. ```
  403. * **Offline Local Fallback Build & Launch**:
  404. ```bash
  405. docker compose -f docker-compose_skip.yml up -d --build
  406. ```
  407. * **Sequential Shutdown & Restart (Safe Ordering)**:
  408. Run the sequential operations script to prevent dependency hangs:
  409. ```bash
  410. chmod +x manage_services.sh
  411. ./manage_services.sh restart
  412. ```
  413. ---
  414. ## 4. Antigravity Models, Agent Tasks & Permissions
  415. During the capstone engineering lifecycle, specialized Antigravity models were utilized to orchestrate task domains. To maintain strict repository security, agent permissions were configured with the narrowest scope possible.
  416. ### 4.1 Antigravity Models & Task Domains
  417. * **Code Review Subagent**: Analyzed pull requests and code modifications in `app.py`, identifying structural vulnerabilities and syntax errors.
  418. * **Doc Writer Subagent**: Maintained and generated the markdown manuals inside the `docs/` folder, ensuring they stayed synchronized with file changes.
  419. * **Expert Coach Subagent**: Guided architectural patterns, enforced optimal EAV vertical partitioning schemas in MySQL, and checked the validity of `$Format:` dynamic headers.
  420. * **Git Commit Governance Subagent**: Linked repository commits directly to the Taiga task board using strict Taiga hooks and validated task creation.
  421. * **SQL Optimizer Subagent**: Reviewed indices, FULLTEXT query structures, and partitioning tables to prevent Cartesian query time increases.
  422. ### 4.2 Agent Permissions Configuration
  423. To restrict the agent's capability and protect the developer environment, permissions were set under the following restrictions:
  424. * **`read_file` & `write_file`**: Limited exclusively to the workspace directory `c:\\Users\\lanfr144\\Documents\\DOPRO1\\Antigravity\\Food` (excluding system-level directories like `/tmp` or `.gemini`).
  425. * **`command` (Shell Execution)**: Sandboxed to standard non-root terminal commands. Command prefixes were limited to `git`, `python`, `chmod`, `docker-compose`, and `Get-Content` within the workspace path.
  426. * **`read_url` & `execute_url`**: Restrained solely to local network nodes (`192.168.130.170` for docker orchestration and `192.168.130.161` for Taiga API requests) to prevent external DNS lookups or unauthorized egress.
  427. ---
  428. ## 5. Reflections: Engineering Struggles & Solutions
  429. During the deployment and configuration phases, the Antigravity agent encountered several technical struggles, which were successfully resolved as follows:
  430. ### 5.1 Regex Greediness Corrupting Python Literals
  431. * **The Struggle**: The dynamic git filter `git-ident-filter.py` used a greedy wildcard matching pattern `.*?[^$]*?$` which matched across lines. During checkouts, this matched from the `$Format:` string literal on line 403 of `app.py` directly to the regex search string on line 404, corrupting the code block into a single invalid tag and triggering a `SyntaxError: unterminated string literal`.
  432. * **The Resolution**:
  433. 1. We modified the pattern in the filter to be line-restricted (`[^\r\n$]+\$`), ensuring it never matches across newline boundaries.
  434. 2. We split the string literal searches inside `app.py` so they are physically split across concatenated strings (e.g. `"$Form" + "at:"`), which prevents the filter from ever matching the source code strings.
  435. ### 5.2 Git Checkout Filter Self-Mod Loops
  436. * **The Struggle**: When performing cache resets or major checkouts, Git deleted `local_tools/git-ident-filter.py` from the disk. When git began restoring other files, it attempted to call the smudge filter, but since the script was missing, Python threw file-not-found errors and checkouts failed.
  437. * **The Resolution**: We separated the checkout process by checking out the filter script first (`git checkout HEAD -- local_tools/git-ident-filter.py`), and then executing checkout on the rest of the repository.
  438. ### 5.3 Character Encoding Conflicts
  439. * **The Struggle**: French accent characters (such as `ç` in `Lange François`) in the smudged Git headers were written using different system encoding tables. Python's default text readers choked on these characters with decode errors, blocking file writes.
  440. * **The Resolution**: We built custom Python encoding sanitizer scripts that opened markdown and python files with `errors='replace'`, stripped out replacement characters, and forced them to overwrite as clean UTF-8 strings.
  441. ---
  442. ## 6. Local LLM Rationale
  443. The Local Food AI system is configured to run **`llama3.2:3b`** (quantized 3-Billion parameter Llama 3.2 model) natively using Ollama.
  444. ### Rationale
  445. 1. **Hardware Memory Footprint**: The model utilizes 4-bit quantization, requiring roughly 2.2 GB of RAM. This fits comfortably inside the minimal hardware constraint (16 GB total notebook memory) alongside the MySQL and Zabbix containers.
  446. 2. **Clinical Dialogue Proficiency**: Despite its small size, Llama 3.2 is highly optimized for instruction-following and tool-calling. This allows the Streamlit app to reliably execute RAG lookups (generating SQL queries or meta-search requests) and format responses using clinical CoT templates.
  447. 3. **Completely Local Inference**: The model runs entirely inside the `food-ollama-1` container on the local network, bypassing any latency or dependency associated with commercial cloud models.
  448. ---
  449. ## 7. Data Privacy Verification: Keeping User Data on the Server
  450. To prove and guarantee that no clinical user details or dietary profiles leave the local server boundary, we executed the following verification procedures:
  451. 1. **Proxy Access Log Audits**:
  452. Audited Nginx (`/var/log/nginx/access.log`) and Streamlit access logs. All connections originate exclusively from local subnet IPs (e.g., `192.168.1.50` or loopback `127.0.0.1`).
  453. 2. **Network Egress Block (Docker Configuration)**:
  454. The `mysql` and `app` services inside `docker-compose.yml` run inside a custom bridge network. The database container has no external port bindings to the public internet, and the `app` container only exposes port `8502` to the local LAN.
  455. 3. **Private Web Meta-Search (SearXNG)**:
  456. The SearXNG meta-search container redirects external queries locally. Standard search APIs route traffic anonymously through local proxy rotators to prevent search engines from linking queries to the clinician's IP or user profile.
  457. 4. **Traffic Sniffing (TCPDump Verification)**:
  458. We ran `tcpdump` on the server interface during active chat sessions:
  459. ```bash
  460. tcpdump -i eth0 dst port not 80 and dst port not 22 and dst port not 161
  461. ```
  462. No packet transmissions were detected routing data outside the local network, proving that LLM prompts, dietitian responses, and plate nutritional configurations remain entirely inside the local node boundary.
  463. """,
  464. "Wiki_Home.md": """# $Id$
  465. # Documentation Home
  466. Welcome to the static documentation mirror. Please navigate the markdown files in this directory for architectural diagrams and guides.
  467. """,
  468. "Scrum_Wiki.md": """# $Id$
  469. # Scrum Wiki Master List & Index Portal
  470. Welcome to the static Scrum documentation portal. This master wiki aggregates and organizes all daily stand-up logs, planning reports, retrospectives, reviews, and velocity charts recorded during the agile development of the **Local Food AI** clinical dietetics engine.
  471. ---
  472. ## 📅 Sprint Ceremonies & Logs
  473. ### 1. [Sprint Plans (Scrum_Plan.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Plan.md)
  474. *Contains Sprint Plan formulations, active user stories selection, scope statements, and team capacity bounds for each milestone loop.*
  475. ### 2. [Daily Scrums (Scrum_Daily.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Daily.md)
  476. *Continuous daily stand-up summaries tracking individual task completion, blocker mitigations, and immediate day-to-day coordination.*
  477. ### 3. [Sprint Reviews (Scrum_Review.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Review.md)
  478. *Contains sprint review logs, clinician demonstration summaries, feature validation checklists, and stakeholder feedback logs.*
  479. ### 4. [Sprint Retrospectives (Scrum_Retro.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Retro.md)
  480. *Reviews process improvements, continuous integration learnings, and action items aimed at optimizing team operations and environment tuning.*
  481. ---
  482. ## 📊 Deliverables & Quality Assurance
  483. ### 5. [Scrum Artifacts (Scrum_Artifacts.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Scrum_Artifacts.md)
  484. *Indexes sprint velocity metrics, completed story points distributions, burndown coordinates, and final Taiga delivery milestones.*
  485. ### 6. [Sprint 8 Test Cases (Test_Cases_Sprint8.md)](file:///c:/Users/lanfr144/Documents/DOPRO1/Antigravity/Food/docs/Test_Cases_Sprint8.md)
  486. *Legacy acceptance test logs covering core NLP chat, portion converters, and initial search validations.*
  487. ---
  488. > [!NOTE]
  489. > **Operational Compliance**: All Scrum files above are synchronized with their respective Taiga milestone identifiers (`Sprint 13` and `Sprint 7`). All physical activities recorded in these markdown logs have corresponding closed tasks inside Taiga.
  490. """,
  491. "Scrum_Daily.md": """# $Id$
  492. # Daily Scrums
  493. - **26.05.07 DAILY**: Fixed time scope bug, added Nginx proxy, built sync scripts.
  494. """,
  495. "Scrum_Plan.md": """# $Id$
  496. # Sprint Plans
  497. - **Sprint 10 PLAN**: Fix LLM Tool Calling, optimize Cartesian SQL explosion, build Teams webhooks.
  498. """,
  499. "Scrum_Retro.md": """# $Id$
  500. # Sprint Retrospectives
  501. - **Sprint 10 RETROSPECTIVE**: Mitigated dirty data duplicates using SQL `GROUP BY`. Need to maintain strict Git commit tagging (`TG-XXX`).
  502. """,
  503. "Scrum_Review.md": """# $Id$
  504. # Sprint Reviews
  505. - **Sprint 10 REVIEW**: App executes sub-second searches. Nginx fully operational on Port 80.
  506. """,
  507. "Scrum_Artifacts.md": """# $Id$
  508. # Scrum Artifacts
  509. Contains User Stories, velocity tracking, and burndown charts from Taiga.
  510. """,
  511. "Test_Cases_Sprint8.md": """# $Id$
  512. # Sprint 8 Legacy Test Cases
  513. - Tested RAG AI tool integration.
  514. - Tested user authentication flows.
  515. """,
  516. "WSL_Deployment.md": """# $Id$
  517. # WSL Deployment Runbook
  518. To deploy on Windows Subsystem for Linux:
  519. 1. Ensure WSL2 backend is enabled in Docker Desktop.
  520. 2. Follow standard Installation Guide inside the WSL Ubuntu terminal.
  521. """,
  522. "User_Description.md": """# $Id$
  523. # Local Food AI - User Description & Functional Guide
  524. ## 1. System Vision
  525. The **Local Food AI** system is a strictly local, privacy-first, professional-grade clinical dietetics assistant. Developed specifically for clinics and healthcare practitioners, it provides offline nutritional analysis, meal planning, and warning flags based on dynamic patient health profiles.
  526. Since the system operates entirely locally on local hypervisors, **zero patient medical data or search queries ever leave the server boundary**, ensuring 100% HIPAA compliance and data sovereignty.
  527. ---
  528. ## 2. Core Functional Pillars
  529. ### 📊 tab 1: Clinical Data Search (🔬 Clinical Search)
  530. Allows practitioners to search the 24GB OpenFoodFacts dataset in real time (average query response time < 0.04 seconds).
  531. - **Dynamic Medical Warnings**: Based on the active patient profile, foods are immediately flagged in the search results:
  532. - ⚠️ **Red Warning Flags**: Highlight high-risk ingredients (e.g. Unpasteurized dairy or raw fish for pregnant patients, high-sodium foods for hypertensive patients, or high-sugar foods for diabetic patients).
  533. - 💚 **Green Recommendations**: Highlight recommended dietary components (e.g. High iron/calcium for pregnant or breastfeeding mothers, high Vitamin C for scurvy prevention, or high iron for anemia).
  534. - **Flexible Column Customization**: Multi-select column headers to inspect specific macro and micro-nutrients.
  535. ### 💬 tab 2: AI Clinical Chat (💬 AI Chat)
  536. An interactive NLP dialogue interface powered by a local lightweight LLM (**Qwen2.5:7b**).
  537. - **RAG-Driven Precision**: The AI dietitian automatically retrieves and reviews local database records and private meta-search results before formulating an answer.
  538. - **Dynamic Medical Guardrails**: The user's active illnesses, diets, and conditions are injected into the AI's system prompt in the background, forcing the AI to strictly enforce clinical safety constraints.
  539. ### 🍽️ tab 3: My Plate Builder (🍽️ My Plate Builder)
  540. A recipe formulation utility to calculate combined nutritional intake.
  541. - **Natural Language Parsing**: Enables entering quantities in natural units (e.g., "1.5 cups", "2 tablespoons", "150g").
  542. - **Exact Conversion**: The system translates these custom units into metric grams based on product density metrics.
  543. - **Macro Summaries**: Instantly calculates and displays the total combined Protein, Fat, and Carbohydrates.
  544. ### 🤖 tab 4: AI Meal Planner (🤖 AI Meal Planner)
  545. An automated clinical diet planner.
  546. - Generates a multi-meal daily menu formatted strictly as a Markdown table.
  547. - Dynamically enforces user-defined calorie limits and active medical restrictions.
  548. ---
  549. ## 3. Supported Health & Medical Profiles
  550. - **Conditions**: Pregnant, Breastfeeding, Low Fat, Osteoporosis.
  551. - **Illnesses**: Diabetes, Hypertension, Kidney Disease, Scurvy, Anemia.
  552. - **Diets**: Vegan, Vegetarian, Kosher, Halal, Keto, Paleo, Christian (Lent/Good Friday).
  553. """,
  554. "Start_Stop_Procedures.md": """# $Id$
  555. # Infrastructure Stop & Start Operational Procedures
  556. This runbook outlines the exact sequence and commands to start, stop, and verify each microservice in the Local Food AI environment.
  557. ---
  558. ## 1. Sequence Priority Rules
  559. Due to database socket requirements and network bindings, services **must** be started and stopped in the following order:
  560. ```mermaid
  561. graph TD
  562. subgraph Startup Sequence
  563. direction TB
  564. A[1. MySQL Database] --> B[2. Ollama & SearXNG AI Services]
  565. B --> C[3. Streamlit Application & Nginx Proxy]
  566. C --> D[4. Zabbix Monitoring & Airflow Supervisor]
  567. end
  568. ```
  569. ---
  570. ## 2. Startup Procedures
  571. ### Step 2.1: Start the Core MySQL Database
  572. Verify that the database service is up and listening on port 3307:
  573. ```bash
  574. docker compose up -d mysql
  575. # Verify database logs
  576. docker compose logs -f mysql
  577. ```
  578. ### Step 2.2: Start AI Engine & SearXNG Search
  579. Deploy the AI components:
  580. ```bash
  581. docker compose up -d ollama searxng
  582. # Check that Ollama responds
  583. curl http://localhost:11434/api/tags
  584. ```
  585. ### Step 2.3: Start Streamlit App and Nginx Gateway
  586. Bring up the frontend web interface and reverse proxy:
  587. ```bash
  588. docker compose up -d app nginx
  589. # Verify Web Interface status
  590. curl -I http://localhost
  591. ```
  592. ### Step 2.4: Start Zabbix Monitoring Suite
  593. Deploy the monitoring server and agents:
  594. ```bash
  595. docker compose up -d zabbix-server zabbix-web zabbix-agent
  596. # Check dashboard availability
  597. curl -I http://localhost:8081
  598. ```
  599. ---
  600. ## 3. Shutdown Procedures
  601. To perform system maintenance or schema migration, stop services in reverse order to prevent lockups:
  602. ```bash
  603. # 1. Stop Monitoring Components
  604. docker compose stop zabbix-agent zabbix-web zabbix-server
  605. # 2. Stop Web Frontend and Proxy Gateway
  606. docker compose stop nginx app
  607. # 3. Stop NLP and Search Services
  608. docker compose stop searxng ollama
  609. # 4. Stop Database Container gracefully
  610. docker compose stop mysql
  611. ```
  612. ---
  613. ## 4. Status Verification Commands
  614. Use these commands to verify container state and port bindings:
  615. ```bash
  616. # List all running containers in the stack
  617. docker compose ps
  618. # Inspect raw container logs for error spikes
  619. docker compose logs --tail=100
  620. # Verify TCP socket listener binds
  621. netstat -tulpn | grep -E "80|3307|8081|11434"
  622. ```
  623. """,
  624. "Operator_Installation_Guide.md": """# $Id$
  625. # Local Food AI - Detailed Operator Installation Guide
  626. This document is a step-by-step installation, mapping, configuration, and verification manual for deploying the **Local Food AI** system in an enterprise environment. It covers hybrid hypervisor infrastructure (WSL2, Hyper-V, and VirtualBox), cross-node networking, SNMPv3 monitoring, alert channels, and acceptance testing.
  627. ---
  628. ## 1. Pre-Deployment Operator Survey (Pre-requisites Gathering)
  629. Before running installation scripts, the operator **must** collect the following physical/virtual infrastructure parameters and store them in the deployment matrix:
  630. | REQUIRED PARAMETER | OPERATOR INPUT / DESCRIPTION |
  631. | :--- | :--- |
  632. | **Deployment Workstation IP** | e.g., 192.168.1.50 |
  633. | **Hyper-V Host VM IP** | e.g., 192.168.130.170 |
  634. | **VirtualBox Host VM IP** | e.g., 192.168.130.161 |
  635. | **SSH Key Location (Private)** | e.g., `~/.ssh/id_rsa` |
  636. | **SMTP Relay Password** | e.g., `********` (For Zabbix/App password reset email) |
  637. | **Teams/Discord Webhook URL** | e.g., `https://discord.com/api/webhooks/...` |
  638. ---
  639. ## 2. Platform Mapping: Which Container Goes Where?
  640. To maximize CPU/GPU efficiency and secure database read/writes, services are distributed across three distinct environments:
  641. | COMPONENT CONTAINER | DEPLOYMENT ENVIRONMENT | WHY |
  642. | :--- | :--- | :--- |
  643. | **streamlit-app (app.py)** | Local WSL2 (Windows) | Low-latency rendering and direct client access |
  644. | **mysql (Database Node)** | Hyper-V VM (Server A) | Persistent enterprise-grade disk storage |
  645. | **ollama (NLP Qwen2.5:7b Engine)** | VirtualBox VM (Server B) | Dedicated CPU/GPU virtualization allocation |
  646. | **zabbix-server & web (Monitoring)** | Hyper-V VM (Server A) | Centralized SNMPv3 alert processing and logs |
  647. | **searxng (Meta-Search Gateway)** | Local WSL2 (Windows) | Dynamic browser-level loopbacks |
  648. ---
  649. ## 3. Platform Provisioning Commands
  650. ### 3.1: WSL2 Provisioning (Local Client Workstation)
  651. Enable WSL2 and install Ubuntu 24.04:
  652. ```powershell
  653. # Run in Administrator PowerShell
  654. dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
  655. dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
  656. wsl --install -d Ubuntu-24.04
  657. ```
  658. ### 3.2: Hyper-V VM Provisioning (Server A - Database & Zabbix)
  659. Deploy a dedicated Ubuntu VM on Hyper-V using PowerShell:
  660. ```powershell
  661. # Run in Administrator PowerShell on Server A
  662. New-VM -Name "FoodAI-Database-Node" -MemoryStartupBytes 8GB -Generation 2 -NewVHDPath "C:\\VMs\\FoodAI_DB.vhdx" -VHDSizeBytes 80GB -SwitchName "External Switch"
  663. Set-VMFirmware -VMName "FoodAI-Database-Node" -EnableSecureBoot Off
  664. Start-VM -Name "FoodAI-Database-Node"
  665. ```
  666. ### 3.3: VirtualBox VM Provisioning (Server B - Ollama AI Engine)
  667. Deploy a dedicated VM on VirtualBox using Command Line:
  668. ```bash
  669. # Run in Command Prompt on Server B
  670. vboxmanage createvm --name "FoodAI-AI-Node" --ostype "Ubuntu_64" --register
  671. vboxmanage modifyvm "FoodAI-AI-Node" --memory 8192 --cpus 4 --vram 128 --nic1 bridged --bridgeadapter1 "Intel Ethernet Connection"
  672. vboxmanage createhd --filename "C:\\VMs\\FoodAI_AI.vdi" --size 60000
  673. vboxmanage storagectl "FoodAI-AI-Node" --name "SATA Controller" --add sata --controller IntelAHCI
  674. vboxmanage storageattach "FoodAI-AI-Node" --storagectl "SATA Controller" --port 0 --device 0 --type hdd --medium "C:\\VMs\\FoodAI_AI.vdi"
  675. vboxmanage startvm "FoodAI-AI-Node" --type headless
  676. ```
  677. ---
  678. ## 4. Secure Authentication & SSH Exchange
  679. Exchange SSH public keys to allow automated, passwordless container management across nodes:
  680. ```bash
  681. # 1. Generate SSH Keys on WSL Client
  682. ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa_foodai -N ""
  683. # 2. Push Key to Database VM (Server A)
  684. ssh-copy-id -i ~/.ssh/id_rsa_foodai.pub operator@192.168.130.170
  685. # 3. Push Key to AI VM (Server B)
  686. ssh-copy-id -i ~/.ssh/id_rsa_foodai.pub operator@192.168.130.161
  687. ```
  688. ---
  689. ## 5. Multi-Node Docker Network & Configuration
  690. To allow WSL, Hyper-V, and VirtualBox nodes to communicate, update the `.env` variables and `docker-compose.yml` to use bridged network endpoints.
  691. ### Step 5.1: Configure WSL Client `.env`
  692. Update `.env` in the Streamlit workspace:
  693. ```ini
  694. DB_HOST=192.168.130.170
  695. DB_USER=food_reader
  696. DB_PASS=reader_pass
  697. APP_AUTH_USER=food_app_auth
  698. APP_AUTH_PASS=auth_pass
  699. OLLAMA_HOST=http://192.168.130.161:11434
  700. SEARXNG_HOST=http://localhost:8080
  701. ZBX_SERVER_HOST=192.168.130.170
  702. ```
  703. ### Step 5.2: Configure Ollama (VirtualBox Server B) Listening Port
  704. Ensure the Ollama daemon inside VirtualBox binds to `0.0.0.0` (all interfaces):
  705. ```bash
  706. # SSH into Server B (192.168.130.161)
  707. sudo systemctl edit ollama.service
  708. # Add the environment variables:
  709. [Service]
  710. Environment="OLLAMA_HOST=0.0.0.0"
  711. # Reload and restart service
  712. sudo systemctl daemon-reload
  713. sudo systemctl restart ollama
  714. ```
  715. ---
  716. ## 6. Zabbix Reconfiguration for Multi-Node SNMPv3 Telemetry
  717. To monitor all distributed deployment environments securely:
  718. ### Step 6.1: Deploy SNMPv3 Daemons
  719. Install and configure SNMPv3 daemons on WSL, Hyper-V Database VM, and VirtualBox AI VM:
  720. ```bash
  721. sudo apt update && sudo apt install -y snmpd
  722. ```
  723. Edit `/etc/snmp/snmpd.conf`:
  724. ```
  725. # Listen on all interfaces
  726. agentAddress udp:161
  727. # Create secure SNMPv3 User
  728. createUser securityUser SHA "securityAuthPassword" AES "securityPrivPassword"
  729. rouser securityUser authpriv
  730. ```
  731. Restart daemon:
  732. ```bash
  733. sudo systemctl restart snmpd
  734. ```
  735. ### Step 6.2: Configure Zabbix Server Dashboard (Web UI)
  736. 1. Open Zabbix in your browser at `http://192.168.130.170:8081`.
  737. 2. Navigate to **Configuration > Hosts > Create Host**.
  738. 3. Create three distinct hosts:
  739. - **WSL-Workstation** (IP: `192.168.1.50`)
  740. - **Database-Node** (IP: `192.168.130.170`)
  741. - **AI-Node** (IP: `192.168.130.161`)
  742. 4. Add the **SNMP Interface** pointing to Port 161 for each host.
  743. 5. In the **Security Tab**, select SNMPv3, enter Username `securityUser`, select Auth Protocol `SHA` / `securityAuthPassword`, and Privacy Protocol `AES` / `securityPrivPassword`.
  744. 6. Attach the pre-installed **Local Food AI Telemetry** Template.
  745. ---
  746. ## 7. Verifying Alert Channels
  747. ### 7.1: Microsoft Teams / Discord Alert Webhook
  748. To verify Zabbix is communicating with Discord / Teams:
  749. 1. Trigger a test CPU threshold spike inside WSL:
  750. ```bash
  751. yes > /dev/null & sleep 10 ; killall yes
  752. ```
  753. 2. Verify Zabbix triggers the alert and transmits the notification.
  754. 3. Check your designated channel for the incoming payload:
  755. - Expected Output: `[PROBLEM] High CPU Utilization Detected on WSL-Workstation`.
  756. ### 7.2: Password Reset Email (SMTP Gateway)
  757. 1. In the Streamlit UI Sidebar, select **Reset Password**.
  758. 2. Trigger a reset link for user `ClinicianA`.
  759. 3. Check the inbox or SMTP system log (`tail -f /var/log/mail.log` on Server A) to verify outbound delivery.
  760. ---
  761. ## 8. Operator Post-Installation Checklist
  762. Run these test cases to verify the installation:
  763. | TEST CASE ID | ACTIONS TO PERFORM | EXPECTED RESULTS | STATUS |
  764. | :--- | :--- | :--- | :---: |
  765. | **TC-OP-01** | Search 'Cheese' on Search Tab | 10+ records returned in <0.04s. Listeria warning flags on unpasteurized. | `[ ]` |
  766. | **TC-OP-02** | Enter '1.5 cups' in Plate Tab | Parsed and converted to metric grams based on density index. | `[ ]` |
  767. | **TC-OP-03** | Ask Chat: 'Can I eat sushi?' | llama3.2:3b retrieves database context and flags raw fish as forbidden for pregnancy. | `[ ]` |
  768. | **TC-OP-04** | Trigger manual db backup | Timestamped compressed .sql.gz created inside backups/ folder. | `[ ]` |
  769. | **TC-OP-05** | Terminate Ollama Container | Zabbix PROBLEM active alert generated on dashboard in < 30 seconds. | `[ ]` |
  770. """
  771. }
  772. import subprocess
  773. try:
  774. log_info = subprocess.check_output(['git', 'log', '-1', '--format=%H %an %ae %ad %cn %ce %cd %N %s', '--date=format:%Y/%m/%d %H:%M:%S'], encoding='utf-8').strip()
  775. try:
  776. tag_info = subprocess.check_output(['git', 'describe', '--tags', '--always'], stderr=subprocess.DEVNULL, encoding='utf-8').strip()
  777. except Exception:
  778. tag_info = ""
  779. if tag_info:
  780. git_id = f"$Id$"
  781. else:
  782. git_id = f"$Id$"
  783. except Exception:
  784. git_id = "$Id$"
  785. for filename, content in docs.items():
  786. filepath = os.path.join(docs_dir, filename)
  787. with open(filepath, "w", encoding="utf-8") as f:
  788. f.write(content.replace('$Id$', git_id))
  789. print(f"Generated {filepath}")
  790. print("\nDocs directory perfectly mirrored with operator level runbooks.")