Upload README.md

#1
by mahendra0120 - opened
Files changed (1) hide show
  1. README.md +213 -109
README.md CHANGED
@@ -1,109 +1,213 @@
1
- # ASP — Agentic Serial-crime Profiler
2
-
3
- A two-agent Qwen3-VL pipeline (Forensic agent → Profiler agent, wired
4
- together over A2A) that turns case images into a forensic report and
5
- a behavioral profile. An image-viewer MCP server lets the Profiler
6
- agent look at its Advanced reference images, results are stored in
7
- PostgreSQL, and a local RAG lookup runs over `forensic_knowledge/`.
8
-
9
- ## Running on RunPod
10
-
11
- **Pod requirements**
12
- - A GPU pod with a **network volume mounted at `/workspace`** (model
13
- weights, the uv cache and Postgres backups live there so they
14
- survive pod restarts).
15
- - HTTP port **7860** exposed in the pod settings (that's the Gradio UI;
16
- you'll reach it through RunPod's proxy URL for that port).
17
- - Any Ubuntu-based image with an NVIDIA driver. Running as root without
18
- `sudo` is fine — the scripts handle both.
19
-
20
- **First run**
21
- ```bash
22
- cd /workspace
23
- git clone https://github.com/mahendra0120/AgenticSP.git
24
- cd AgenticSP/ASP
25
- cp .env.example .env # set HF_TOKEN if either model repo is private/gated
26
- bash start.sh
27
- ```
28
-
29
- **After every pod restart** — just run `bash start.sh` again. It is
30
- idempotent and does, in order:
31
-
32
- | Step | Script | What it does |
33
- |---|---|---|
34
- | 1 | `setup_env.sh` | Installs `uv` if missing, points the HF / uv caches at `/workspace`, exports the env vars |
35
- | 2 | `setup_postgres.sh` | Installs/starts Postgres, creates the `asp` role + DB, restores the latest backup, starts the background backup loop |
36
- | 3 | `uv sync --frozen` | Installs Python deps (fast after the first run — cached on the volume) |
37
- | 4 | `main.py` | Starts the Gradio UI. Press **🚀 Start Servers** in it to launch the Profiler and Forensic agent servers (`a2a_server.py`) |
38
-
39
- **Environment variables** (set by `setup_env.sh`)
40
-
41
- | Var | Value |
42
- |---|---|
43
- | `HF_HOME` | `/workspace/hf_cache` |
44
- | `HF_HUB_OFFLINE` | `1` once the cache has models; left unset on an empty cache so the first run can download |
45
- | `PROFILER_AGENT_PORT` | `8011` |
46
- | `FORENSIC_AGENT_PORT` | `8002` |
47
-
48
- `HF_TOKEN` is a credential and lives only in `.env` (gitignored) —
49
- never in a script or committed file. It's only needed for the first
50
- download of a private/gated repo; once weights are cached the app runs
51
- offline and the token isn't used.
52
-
53
- **Logs** — `server_logs/{profiler,forensic}_server.log`. Each launch
54
- starts a fresh log and keeps the previous one as `*.log.prev`, so a
55
- crash trace survives a restart. If the Profiler fails, its traceback
56
- is in `profiler_server.log`; `exit_codes.log` records how each server
57
- process exited (e.g. SIGKILL from the OOM killer).
58
-
59
- **Database backups** — a snapshot is written to
60
- `/workspace/pg-backups/latest.dump` every 5 minutes. Run
61
- `bash backup_postgres.sh` for an immediate one before deliberately
62
- stopping the pod.
63
-
64
- `setup_env.sh` must be **sourced** (`source setup_env.sh`), not
65
- executed, if you run it by hand; `start.sh` does that for you.
66
-
67
- The scripts and the application live in `ASP/`; run every command above
68
- from that folder.
69
-
70
- ## Profiler reference version
71
-
72
- The **Profiler reference version** dropdown in the UI controls how the
73
- Profiler agent uses its training material. The 5 Basic reference pages
74
- are always attached; the choice is about the 23 Advanced pages, which the
75
- Profiler reads through the image-viewer MCP tools.
76
-
77
- | Option | What happens |
78
- |---|---|
79
- | **Auto** (default) | The model decides whether the Advanced pages are worth consulting |
80
- | **Basic** | The viewer tools are removed for the run; only the 5 Basic pages are used |
81
- | **Advanced** | The Profiler is told it must consult the relevant Advanced sections before writing |
82
-
83
- Basic is enforced (the model is not offered the tools). Advanced is an
84
- instruction to the model, not something the code can force; if the model
85
- skips the viewer, `profiler_server.log` records a warning.
86
-
87
- The version is saved with the case. If you rerun a saved case with a
88
- different version, only the Profiler is rerun; the Forensic report, RAG
89
- lookup and reference summaries are reused. Cases saved before this option
90
- existed count as Auto.
91
-
92
- ## Project layout
93
-
94
- The application is in `ASP/`; the paths below are relative to it. The
95
- repository root also holds `pg-data/` (the Postgres data directory) and
96
- `pg-backups/` (`latest.dump` and `autobackup.log`).
97
-
98
- | Path | Role |
99
- |---|---|
100
- | `main.py` | Gradio UI + pipeline orchestration (Forensic → RAG ‖ Profiler), server start/stop/restart |
101
- | `a2a_server.py` | Serves one agent over A2A: `python a2a_server.py forensic\|profiler` |
102
- | `a2a_client.py` | Minimal streaming A2A client used by `main.py` |
103
- | `qwen_agents/` | The two agents and `model_utils.py` (`QwenVLModel`: local Qwen3-VL inference as a pydantic-ai model) |
104
- | `qwen_agents/Profiler_agent/image_viewer_mcp.py` | Stdio MCP server that shows the Profiler the 23 Advanced reference images, one section at a time (`list_sections`, `view_section`, `view_image`) |
105
- | `reference_version.py` | The Basic / Advanced / Auto choice: dropdown options and the marker the Profiler reads from its message |
106
- | `octen_rag.py` | Embedding retrieval + trauma-type selection over `forensic_knowledge/` |
107
- | `pipeline_state.py`, `db.py` | Postgres checkpointing (`CaseStore`, `CheckpointDB`) so interrupted runs can resume |
108
- | `example_images.py` | Thumbnail gallery of previously uploaded photos |
109
- | `env_defaults.py` | Loads `.env` and sets cache/port defaults before anything imports `huggingface_hub` |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Agentic_Serial-killer_Profiler
2
+
3
+ A two-agent, multimodal pipeline that turns case photographs into a structured forensic report and then, a behavioral profile. Both agents are built on **Qwen3-VL-8B-Thinking**, run locally, and talk to each other over the **A2A (Agent-to-Agent)** protocol. A **Gradio** app drives the workflow, **PostgreSQL** checkpoints every step so interrupted runs can resume, and a local **RAG** layer adds reference summaries on injury types for educational purposes.
4
+
5
+ > **Prototype for research and education.** Outputs can be wrong and must never be treated as forensic findings, evidence, or a basis for accusing anyone. See [Disclaimer](#disclaimer).
6
+
7
+ ---
8
+
9
+ ## Table of contents
10
+
11
+ - [How it works](#how-it-works)
12
+ - [Models](#models)
13
+ - [Requirements](#requirements)
14
+ - [Quick start (RunPod)](#quick-start-runpod)
15
+ - [Running without RunPod](#running-without-runpod)
16
+ - [Using the app](#using-the-app)
17
+ - [Configuration](#configuration)
18
+ - [Project layout](#project-layout)
19
+ - [Logs, backups and troubleshooting](#logs-backups-and-troubleshooting)
20
+ - [Disclaimer](#disclaimer)
21
+
22
+ ---
23
+
24
+ ## How it works
25
+
26
+ ```
27
+ Gradio UI (port 7860)
28
+ | up to 15 images + optional context
29
+ v
30
+ PipelineRun -- case id = SHA-256(images + context)[:12] -- PostgreSQL checkpoints
31
+ |
32
+ |-- 1. Forensic agent (A2A, port 8002)
33
+ | -> Forensic Report
34
+ |
35
+ '-- 2. Run concurrently
36
+ |-- RAG: read the EOT section, select reference files (FAISS + Octen embeddings)
37
+ | -> Reference summaries section: Forensic agent outputs each summary of listed injury
38
+ |
39
+ '-- Profiler agent (A2A, port 8011): images + forensic report
40
+ (+ MCP image viewer for the Advanced reference pages)
41
+ |
42
+ v
43
+ Final report -> pipeline_result.md and the Postgres 'final' step
44
+ ```
45
+
46
+ - **Forensic agent**: Reads only the photographs and writes a forensic-style report that includes every type of each listed injury.
47
+ - **RAG step**: These aforementioned listed injury types would be selecting files from `ASP/forensic_knowledge/` via keyword trigger function, and the Forensic agent writes a short educational summary of each selected files.
48
+ - **Profiler agent**: Treats the forensic report as evidence and writes a five-section behavioral profile: Crime Scene Report, Victimology, Organization Level, Offender Typology, Rationale & Confidence.
49
+ - **Resumable**: Every step is saved to Postgres, so a crash or pod restart does not lose a long run.
50
+
51
+ ## Models
52
+
53
+ The code refers to models only by Hugging Face id and downloads them on first start.
54
+
55
+ | Role | Model | Notes |
56
+ |---|---|---|
57
+ | Forensic agent | [`mahendra0120/Forensic-Agent-4.0-2026-09-08_14.31.12`](https://huggingface.co/mahendra0120/Forensic-Agent-4.0-2026-09-08_14.31.12) | LoRA adapter (r=8, SFT) on the Profiler's base model; merged at load time |
58
+ | Profiler agent | [`Kizzington/Qwen3-VL-8B-Thinking-heretic`](https://huggingface.co/Kizzington/Qwen3-VL-8B-Thinking-heretic) | About 17.5 GB in 4 shards; abliterated variant of Qwen3-VL-8B-Thinking |
59
+ | Processor / tokenizer | [`Qwen/Qwen3-VL-8B-Thinking`](https://huggingface.co/Qwen/Qwen3-VL-8B-Thinking) | Config and tokenizer files only |
60
+ | RAG embeddings | [`Octen/Octen-Embedding-0.6B`](https://huggingface.co/Octen/Octen-Embedding-0.6B) | 1024-dim, runs on CPU |
61
+
62
+ The Hugging Face repository [`mahendra0120/Agentic_Serial-killer_Profiler`](https://huggingface.co/mahendra0120/Agentic_Serial-killer_Profiler) contains a ready-made `hf_cache/` folder with these models that cannot be found in the [`github repo`](https://github.com/mahendra0120/Agentic_Serial-killer_Profiler). It is not needed if the machine can download from the Hub.
63
+
64
+ ## Requirements
65
+
66
+ - Linux with an NVIDIA GPU and driver. **Two GPUs are recommended**: each 8B model needs about 17.5 GB for weights in bfloat16, so one GPU holding both needs roughly 35 GB before activations. With one smaller GPU, enable 4-bit loading (see [Configuration](#configuration)).
67
+ - Python 3.13 (installed automatically by `uv`)
68
+ - [`uv`](https://docs.astral.sh/uv/) package manager
69
+ - PostgreSQL
70
+ - Disk space for model weights (about 20 GB) and the Python environment
71
+ - A Hugging Face token (`HF_TOKEN`) only if a model repo is private or gated
72
+
73
+ ## Quick start (RunPod)
74
+
75
+ The scripts target a RunPod GPU pod with a **network volume mounted at `/workspace`** (it keeps model weights, the uv cache and database backups across restarts) and **HTTP port 7860** exposed.
76
+
77
+ ```bash
78
+ cd /workspace
79
+ git clone https://github.com/mahendra0120/Agentic_Serial-killer_Profiler.git
80
+ cd Agentic_Serial-killer_Profiler/ASP
81
+ cp .env.example .env # add HF_TOKEN if needed
82
+ bash start.sh
83
+ ```
84
+
85
+ `start.sh` is safe to re-run after every pod restart. It does, in order:
86
+
87
+ | Step | Script | What it does |
88
+ |---|---|---|
89
+ | 1 | `setup_env.sh` | Installs `uv` if missing, points the Hugging Face and uv caches at `/workspace`, sets ports, switches the Hub to offline mode once models are cached |
90
+ | 2 | `setup_postgres.sh` | Installs and starts PostgreSQL, creates the `asp` role and database, restores `/workspace/pg-backups/latest.dump`, starts a backup loop (every 5 minutes) |
91
+ | 3 | `uv sync --frozen` | Installs Python dependencies from the lock file |
92
+ | 4 | `main.py` | Starts the Gradio UI on port 7860 |
93
+
94
+ Open the pod's proxy URL for port 7860, then press **Start Servers** (see below). The first start downloads the models, so the agent servers can take several minutes to become ready.
95
+
96
+ ## Running without RunPod
97
+
98
+ `setup_env.sh` and `setup_postgres.sh` expect `/workspace`. On another machine you can either create that directory (`sudo mkdir -p /workspace`) and use `start.sh` as above, or set things up by hand:
99
+
100
+ ```bash
101
+ git clone https://github.com/mahendra0120/Agentic_Serial-killer_Profiler.git
102
+ cd Agentic_Serial-killer_Profiler/ASP
103
+ cp .env.example .env
104
+
105
+ # 1. PostgreSQL (matches the defaults in db.py / .env.example)
106
+ sudo -u postgres psql -c "CREATE ROLE asp_user LOGIN PASSWORD 'asp_password';"
107
+ sudo -u postgres psql -c "CREATE DATABASE asp OWNER asp_user;"
108
+ # the pipeline_steps table is created automatically on first connection
109
+
110
+ # 2. Environment
111
+ export HF_HOME="$HOME/hf_cache" # where models are stored
112
+ export PROFILER_AGENT_PORT=8011
113
+ export FORENSIC_AGENT_PORT=8002
114
+
115
+ # 3. Install and run
116
+ uv sync --frozen
117
+ uv run python main.py
118
+ ```
119
+
120
+ If you change the database credentials, set `DATABASE_URL` in `.env`.
121
+
122
+ **Optional: reuse the pre-downloaded cache.** To copy the models from the [`Hugging Face repository`](https://huggingface.co/mahendra0120/Agentic_Serial-killer_Profiler) instead of downloading each one from its own repo:
123
+
124
+ ```bash
125
+ pip install -U huggingface_hub
126
+ hf download mahendra0120/Agentic_Serial-killer_Profiler \
127
+ --include "hf_cache/hub/*" --local-dir /workspace
128
+ ```
129
+
130
+ The repository stores each file twice (under `blobs/` and `snapshots/`), so this download is larger than the weights themselves. Letting the first run fetch each model from the Hub is usually simpler.
131
+
132
+ ## Using the app
133
+
134
+ 1. **Start Servers.** Launches the Forensic and Profiler agent servers as separate processes. The status box shows each port and GPU assignment. **Stop Servers** shuts them down.
135
+ 2. **Add images.** Upload or click thumbnails in the *Examples* gallery to reuse earlier uploads, up to 15 photographs.
136
+ 3. **Add context (optional).** A short note about the scene or setting is passed to the Forensic agent.
137
+ 4. **Choose the Profiler reference version.**
138
+ - *Auto* (default): the model decides whether to consult the Advanced pages.
139
+ - *Basic*: only the 5 Basic reference images are used; the viewer tools are removed.
140
+ - *Advanced*: the Profiler is instructed to consult the 23 Advanced pages first. This is an instruction, not something the code can force; a warning is logged if the model skips it.
141
+ 5. **Run Pipeline.** Output streams into the Forensic, Profiler and Reference Summaries panels. The combined report is shown under *Full Result* and saved to `pipeline_result.md`.
142
+
143
+ **Resuming.** Progress is saved to Postgres under a case id derived from the images and context, so running the same inputs again finds the same case. Choose how to treat saved work:
144
+
145
+ | Option | Behavior |
146
+ |---|---|
147
+ | Resume; continue partial reports | Finished steps are reused; an interrupted report is continued from where it stopped |
148
+ | Resume; use partial reports as-is | Accepts a partial report as complete |
149
+ | Start fresh | Deletes saved progress for the case and starts over |
150
+
151
+ You can also pick a saved case from the dropdown. Changing the reference version on a saved case re-runs only the Profiler. The *Manage saved progress* panel deletes one case, cases older than N days, or all cases (permanent; confirmation box required).
152
+
153
+ ## Configuration
154
+
155
+ Set values in `ASP/.env` (copied from `.env.example`). Secrets such as `HF_TOKEN` belong only there; `.env` is gitignored.
156
+
157
+ | Variable | Default | Purpose |
158
+ |---|---|---|
159
+ | `HF_TOKEN` | unset; You have to manually configure it. | Needed only to download private or gated repos |
160
+ | `HF_HOME` | `/workspace/hf_cache` | Model cache location |
161
+ | `HF_HUB_OFFLINE` | auto | Set to `1` automatically once the cache holds models |
162
+ | `FORENSIC_AGENT_PORT` / `PROFILER_AGENT_PORT` | `8002` / `8011` | Agent server ports |
163
+ | `DATABASE_URL` | `postgresql://asp_user:asp_password@localhost:5432/asp` | Checkpoint database |
164
+ | `FORENSIC_MODEL_ID` / `PROFILER_MODEL_ID` | see [Models](#models) | Swap in different models or adapters |
165
+ | `FORENSIC_GPU` / `PROFILER_GPU` | auto | Pin each agent to a GPU index |
166
+ | `ASP_MULTI_GPU` | `true` | Set to `false` to keep both agents on the default GPU |
167
+ | `FORENSIC_LOAD_IN_4BIT` / `PROFILER_LOAD_IN_4BIT` | `false` | Load the model in 4-bit (nf4) to save memory |
168
+ | `ATTN_IMPLEMENTATION` | `sdpa` | Attention backend |
169
+ | `OCTEN_MODEL_ID` | `Octen/Octen-Embedding-0.6B` | Embedding model |
170
+ | `RAG_REBUILD_ON_STARTUP` | `true` | Rebuild the FAISS index on each server start |
171
+ | `RAG_CHARS` | `0` (no limit) | Truncate long reference files in summaries |
172
+ | `SERVER_READY_TIMEOUT_SECONDS` | `300` | How long to wait for the agent servers to open their ports |
173
+
174
+ With two or more visible GPUs, the Forensic agent uses the first and the Profiler the second.
175
+
176
+ ## Project layout
177
+
178
+ Everything runs from the `ASP/` folder.
179
+
180
+ | Path | Role |
181
+ |---|---|
182
+ | `main.py` | Gradio UI, pipeline orchestration, agent server start/stop/restart |
183
+ | `a2a_server.py` | Serves one agent over A2A: `python a2a_server.py forensic` or `profiler` |
184
+ | `a2a_client.py` | Streaming A2A client used by `main.py` |
185
+ | `qwen_agents/model_utils.py` | `QwenVLModel`: Local Qwen3-VL inference (adapter loading, streaming, tool calls) as a pydantic-ai model |
186
+ | `qwen_agents/Forensic_agent/` | Forensic agent and its system prompt |
187
+ | `qwen_agents/Profiler_agent/` | Profiler agent, `image_viewer_mcp.py`, and the `criminal-behavioral-analysis` skill with its reference images |
188
+ | `octen_rag.py` | Chunking, FAISS index, and trauma-type routing over `forensic_knowledge/` |
189
+ | `forensic_knowledge/` | Seven reference markdown files used for summaries |
190
+ | `pipeline_state.py`, `db.py` | Postgres checkpointing and resume logic |
191
+ | `reference_version.py` | Basic / Advanced / Auto reference-version handling |
192
+ | `example_images.py` | Thumbnail gallery of earlier uploads |
193
+ | `env_defaults.py` | Loads `.env` and sets defaults before Hugging Face libraries are imported |
194
+ | `setup_env.sh`, `setup_postgres.sh`, `start.sh`, `backup_postgres.sh` | Bootstrap, database setup, startup and manual backup |
195
+ | `../pg-backups/` | `latest.dump` and `autobackup.log` | Results from the agentic pipeline are stored and backed up in this PostgreSQL directory |
196
+
197
+ ## Logs, backups and troubleshooting
198
+
199
+ - **Logs:** `ASP/server_logs/forensic_server.log` and `profiler_server.log`. Each launch keeps the previous log as `*.log.prev`. `exit_codes.log` records how each agent process ended (for example `SIGKILL` usually means the GPU or system ran out of memory).
200
+ - **Backups:** The database is dumped to `/workspace/pg-backups/latest.dump` every 5 minutes. Run `bash backup_postgres.sh` for an immediate backup before stopping a pod.
201
+ - **Agent shows "not responding after 300s":** The first start is slow because models download and load(if you haven't downloaded the hf_cache directory from the [`huggingface repo`](https://huggingface.co/mahendra0120/Agentic_Serial-killer_Profiler)). Check the server log, or raise `SERVER_READY_TIMEOUT_SECONDS`.
202
+ - **"process exited early":** Read the matching log. Out-of-memory is the most common cause; Enable 4-bit loading or use two GPUs.
203
+ - **Output starts with `FAILURE:`:** The model ran out of its token budget while reasoning, or generation stalled. Re-run the case (resume mode reuses finished steps).
204
+ - **"Database unavailable":** The pipeline still runs, but progress is not saved. Check that PostgreSQL is running and `DATABASE_URL` is correct.
205
+ - **Models re-download every start:** Make sure `HF_HOME` points at the same persistent folder each time.
206
+ - **Changing models:** If `FORENSIC_MODEL_ID` points to an adapter repo (one containing `adapter_config.json`), the base model named inside it is downloaded and the adapter is merged automatically. Use `ADAPTER_BASE_MODEL_ID` to override the base.
207
+
208
+ ## Disclaimer
209
+
210
+ - This is a **prototype**. The repository contains some fully abliterated vision-language models that can misread images and doesn't follow the system prompt to the fullest. A behavioral profile built on a mistaken forensic report inherits the mistake.
211
+ - Profiles describe a *most likely interpretation* of the evidence and rely on typology frameworks (Palermo/Mastronardi, Holmes & Holmes, organized/disorganized) that are debated and not validated predictors.
212
+ - The base model has had its refusal behavior removed. Run the system only in controlled settings with authorized, lawfully obtained material.
213
+ - Case images, generated reports and database dumps may contain sensitive material. Keep them private, do not commit them, and delete saved cases when finished.