Spaces:
Sleeping
Sleeping
| import hashlib | |
| import sqlite3 | |
| import os | |
| from typing import List, Optional | |
| from fastapi import FastAPI, HTTPException, UploadFile, File | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel | |
| from PyPDF2 import PdfReader | |
| from gtts import gTTS | |
| import uvicorn | |
| from io import BytesIO | |
| import tempfile | |
| # ========================= | |
| # CONFIG | |
| # ========================= | |
| HOST = os.getenv("HOST", "0.0.0.0") | |
| PORT = 7860 | |
| DB_PATH = os.getenv("DB_PATH", "ouroboros_datavault.db") | |
| OWNER = os.getenv("OWNER", "Dwayne Anthony Brian Galloway") | |
| SIGNATURE = os.getenv("SIGNATURE", "DABG-OUROBOROS-SIGNED") | |
| # ========================= | |
| # DATA MODELS | |
| # ========================= | |
| class FactEntry(BaseModel): | |
| date: str | |
| actor: str | |
| description: str | |
| evidenceid: Optional[str] = None | |
| class CaseProject(BaseModel): | |
| name: str | |
| facts: List[FactEntry] | |
| class DamagesInput(BaseModel): | |
| projectid: int | |
| general_damages: float | |
| aggravated_damages: float | |
| exemplary_damages: float | |
| # ========================= | |
| # FASTAPI APP | |
| # ========================= | |
| app = FastAPI( | |
| title="Ouroboros Decision Engine - 2026 Unified Build", | |
| description="Forensic litigation decision-support system powered by Honey Badger Protocol", | |
| version="2026.1.0-OUROBOROS" | |
| ) | |
| # ========================= | |
| # DATABASE | |
| # ========================= | |
| def get_db_connection(): | |
| conn = sqlite3.connect(DB_PATH) | |
| conn.row_factory = sqlite3.Row | |
| return conn | |
| def setup_vault(): | |
| conn = get_db_connection() | |
| conn.executescript(""" | |
| CREATE TABLE IF NOT EXISTS projects ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| name TEXT NOT NULL, | |
| owner TEXT DEFAULT 'Dwayne Anthony Brian Galloway', | |
| status TEXT DEFAULT 'Active', | |
| created_ts TEXT DEFAULT CURRENT_TIMESTAMP | |
| ); | |
| CREATE TABLE IF NOT EXISTS evidencevault ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER NOT NULL, | |
| factdate TEXT NOT NULL, | |
| actor TEXT NOT NULL, | |
| factdescription TEXT NOT NULL, | |
| statutemapping TEXT NOT NULL, | |
| evidencehash TEXT NOT NULL, | |
| exhibitid TEXT NOT NULL | |
| ); | |
| CREATE TABLE IF NOT EXISTS auditlog ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER NOT NULL, | |
| timestamp TEXT DEFAULT CURRENT_TIMESTAMP, | |
| action TEXT NOT NULL, | |
| integrityscore REAL, | |
| hashchain TEXT | |
| ); | |
| CREATE TABLE IF NOT EXISTS regulatory_triggers ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER NOT NULL, | |
| regulator TEXT NOT NULL, | |
| breach_statute TEXT NOT NULL, | |
| severity TEXT NOT NULL, | |
| hook_template TEXT NOT NULL | |
| ); | |
| CREATE TABLE IF NOT EXISTS damages_log ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER NOT NULL, | |
| general_damages REAL, | |
| aggravated_damages REAL, | |
| exemplary_damages REAL, | |
| total_damages REAL, | |
| opa_participation REAL, | |
| timestamp TEXT DEFAULT CURRENT_TIMESTAMP | |
| ); | |
| CREATE TABLE IF NOT EXISTS documents ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER, | |
| filename TEXT, | |
| extracted_text TEXT, | |
| audio_path TEXT, | |
| timestamp TEXT DEFAULT CURRENT_TIMESTAMP | |
| ); | |
| """) | |
| conn.commit() | |
| conn.close() | |
| # ========================= | |
| # STATUTORY BREACH MAPPING | |
| # ========================= | |
| def match_statute_breach(description: str) -> str: | |
| desc = description.lower() | |
| if any(k in desc for k in ["refund", "defect", "warranty", "fault", "brake", "faulty", "non-conforming"]): | |
| return "CRA 2015 s.19(14)" | |
| if any(k in desc for k in ["disability", "adjustment", "wheelchair", "adhd", "discrimination", "reasonable"]): | |
| return "EqA 2010 s.20/s.29" | |
| if any(k in desc for k in ["data", "sar", "dsar", "missing", "call recording", "deleted"]): | |
| return "DPA 2018 s.45/s.170" | |
| if any(k in desc for k in ["lie", "distort", "false", "misled", "fraud", "misrepresent"]): | |
| return "Fraud Act 2006 s.3/s.4" | |
| if any(k in desc for k in ["fca", "ombudsman", "fin", "regulated", "treating customers fairly", "prin"]): | |
| return "FSMA 2000 Sch.17/FCA PRIN 6" | |
| return "General Law (FCA PRIN)" | |
| # ========================= | |
| # DOCUMENT PROCESSOR | |
| # ========================= | |
| async def upload_documents(projectid: int = 0, case_name: str = "Document Intake", files: List[UploadFile] = File(...)): | |
| conn = get_db_connection() | |
| if projectid > 0: | |
| project = conn.execute("SELECT id FROM projects WHERE id = ?", (projectid,)).fetchone() | |
| if not project: | |
| conn.close() | |
| raise HTTPException(status_code=404, detail="Project not found") | |
| target_pid = projectid | |
| is_new = False | |
| else: | |
| cursor = conn.execute("INSERT INTO projects (name, owner) VALUES (?, ?)", (case_name, OWNER)) | |
| target_pid = cursor.lastrowid | |
| is_new = True | |
| hashchain = [] | |
| all_breaches = [] | |
| combined_text = "" | |
| file_results = [] | |
| for idx, upload_file in enumerate(files): | |
| filename = upload_file.filename | |
| ext = os.path.splitext(filename)[1].lower() | |
| extracted_text = "" | |
| try: | |
| content = await upload_file.read() | |
| if ext == ".pdf": | |
| reader = PdfReader(BytesIO(content)) | |
| for page in reader.pages: | |
| page_text = page.extract_text() | |
| if page_text: | |
| extracted_text += page_text + "\n" | |
| elif ext in [".txt", ".md", ".csv"]: | |
| extracted_text = content.decode("utf-8", errors="ignore") | |
| else: | |
| continue | |
| except Exception as e: | |
| file_results.append({"file": filename, "status": f"error: {str(e)}"}) | |
| continue | |
| if not extracted_text.strip(): | |
| file_results.append({"file": filename, "status": "no text extracted"}) | |
| continue | |
| combined_text += f"\n\n--- {filename} ---\n\n" + extracted_text | |
| statute = match_statute_breach(extracted_text) | |
| if statute != "General Law (FCA PRIN)": | |
| all_breaches.append({"file": filename, "statute": statute}) | |
| fact_string = f"2026-06-23|DOCUMENT|{filename}: {extracted_text[:800]}...|DOC-{idx+1}" | |
| fact_hash = hashlib.sha256(fact_string.encode("utf-8")).hexdigest() | |
| hashchain.append(fact_hash) | |
| conn.execute( | |
| """INSERT INTO evidencevault | |
| (projectid, factdate, actor, factdescription, statutemapping, evidencehash, exhibitid) | |
| VALUES (?, ?, ?, ?, ?, ?, ?)""", | |
| (target_pid, "2026-06-23", "DOCUMENT_PROCESSOR", f"{filename}: {extracted_text[:800]}...", statute, fact_hash, f"DOC-{target_pid}-{idx+1}") | |
| ) | |
| file_results.append({"file": filename, "status": "processed", "statute": statute, "chars": len(extracted_text)}) | |
| if hashchain: | |
| conn.execute( | |
| """INSERT INTO auditlog (projectid, action, integrityscore, hashchain) | |
| VALUES (?, ?, ?, ?)""", | |
| (target_pid, f"DOCUMENT_INTAKE_{len(hashchain)}_FILES", 1.0, "|".join(hashchain)) | |
| ) | |
| audio_path = None | |
| tts_text = combined_text[:3000] | |
| if tts_text.strip(): | |
| try: | |
| tts = gTTS(text=tts_text, lang="en", slow=False) | |
| tmp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3", dir="/tmp") | |
| tts.save(tmp_audio.name) | |
| audio_path = tmp_audio.name | |
| conn.execute("INSERT INTO documents (projectid, filename, extracted_text, audio_path) VALUES (?, ?, ?, ?)", | |
| (target_pid, "combined_tts", combined_text[:2000], audio_path)) | |
| except Exception: | |
| pass | |
| conn.commit() | |
| conn.close() | |
| return { | |
| "status": f"{'Created' if is_new else 'Added to'} Project {target_pid}", | |
| "projectid": target_pid, | |
| "files_processed": len(file_results), | |
| "file_results": file_results, | |
| "breaches_detected": len(all_breaches), | |
| "breaches": all_breaches, | |
| "audio_generated": audio_path is not None, | |
| "signature": SIGNATURE | |
| } | |
| async def get_audio(projectid: int): | |
| conn = get_db_connection() | |
| doc = conn.execute("SELECT audio_path FROM documents WHERE projectid = ? ORDER BY id DESC LIMIT 1", (projectid,)).fetchone() | |
| conn.close() | |
| if not doc or not doc["audio_path"]: | |
| raise HTTPException(status_code=404, detail="No audio found") | |
| return FileResponse(doc["audio_path"], media_type="audio/mpeg") | |
| # ========================= | |
| # CORE ENDPOINTS | |
| # ========================= | |
| async def root(): | |
| return {"system": "Ouroboros Litigation Station", "version": "2026.1.0-OUROBOROS", "docs": "/docs", "signature": SIGNATURE} | |
| async def health_check(): | |
| return { | |
| "status": "Operational", | |
| "system": "Ouroboros Decision Engine", | |
| "owner": OWNER, | |
| "version": "2026.1.0-OUROBOROS", | |
| "opa_rate": "20%", | |
| "ip_royalty": "10% (Coding Demon)", | |
| "signature": SIGNATURE | |
| } | |
| async def intake_evidence(case: CaseProject): | |
| conn = get_db_connection() | |
| cursor = conn.execute("INSERT INTO projects (name, owner) VALUES (?, ?)", (case.name, OWNER)) | |
| projectid = cursor.lastrowid | |
| hashchain = [] | |
| for fact in case.facts: | |
| fact_string = f"{fact.date}|{fact.actor}|{fact.description}|{fact.evidenceid or 'NONE'}" | |
| fact_hash = hashlib.sha256(fact_string.encode("utf-8")).hexdigest() | |
| hashchain.append(fact_hash) | |
| statute = match_statute_breach(fact.description) | |
| exhibit_id = fact.evidenceid or f"EX-{len(hashchain)}" | |
| conn.execute( | |
| """INSERT INTO evidencevault | |
| (projectid, factdate, actor, factdescription, statutemapping, evidencehash, exhibitid) | |
| VALUES (?, ?, ?, ?, ?, ?, ?)""", | |
| (projectid, fact.date, fact.actor, fact.description, statute, fact_hash, exhibit_id) | |
| ) | |
| conn.execute( | |
| """INSERT INTO auditlog (projectid, action, integrityscore, hashchain) | |
| VALUES (?, ?, ?, ?)""", | |
| (projectid, "INTAKE_RESTLESS", 1.0, "|".join(hashchain)) | |
| ) | |
| conn.commit() | |
| conn.close() | |
| return { | |
| "status": "Intake Complete", | |
| "projectid": projectid, | |
| "evidence_count": len(case.facts), | |
| "integrity": 1.0, | |
| "signature": SIGNATURE | |
| } | |
| async def run_temporal_cascade(projectid: int): | |
| conn = get_db_connection() | |
| evidence_rows = conn.execute("SELECT * FROM evidencevault WHERE projectid = ?", (projectid,)).fetchall() | |
| if not evidence_rows: | |
| conn.close() | |
| raise HTTPException(status_code=400, detail="No evidence found") | |
| regulatory_triggers = [] | |
| for evidence in evidence_rows: | |
| statute = evidence["statutemapping"] | |
| if "CRA" in statute: regulatory_triggers.append({"regulator": "FCA", "breach": statute}) | |
| if "EqA" in statute: regulatory_triggers.append({"regulator": "EHRC", "breach": statute}) | |
| if "DPA" in statute: regulatory_triggers.append({"regulator": "ICO", "breach": statute}) | |
| if "Fraud" in statute: regulatory_triggers.append({"regulator": "NCA", "breach": statute}) | |
| if "FSMA" in statute: regulatory_triggers.append({"regulator": "FCA", "breach": statute}) | |
| module_passes = 15 | |
| integrity_score = min(1.0, module_passes / 15) | |
| ownergate = "OPEN" if integrity_score >= 0.8 else "LOCKED" | |
| conn.execute( | |
| """INSERT INTO auditlog (projectid, action, integrityscore) | |
| VALUES (?, ?, ?)""", | |
| (projectid, "TEMPORAL_CASCADE_1440", integrity_score) | |
| ) | |
| for trigger in regulatory_triggers: | |
| conn.execute( | |
| """INSERT OR IGNORE INTO regulatory_triggers | |
| (projectid, regulator, breach_statute, severity, hook_template) | |
| VALUES (?, ?, ?, ?, ?)""", | |
| (projectid, trigger["regulator"], trigger["breach"], "HIGH", | |
| f"Complaint hook for {trigger['regulator']} - {trigger['breach']}") | |
| ) | |
| conn.commit() | |
| conn.close() | |
| return { | |
| "status": "Cascade Complete", | |
| "projectid": projectid, | |
| "integrity_score": integrity_score, | |
| "ownergate": ownergate, | |
| "regulatory_triggers": len(regulatory_triggers), | |
| "signature": SIGNATURE | |
| } | |
| async def generate_court_pack(projectid: int): | |
| conn = get_db_connection() | |
| project = conn.execute("SELECT * FROM projects WHERE id = ?", (projectid,)).fetchone() | |
| if not project: | |
| conn.close() | |
| raise HTTPException(status_code=404, detail="Project not found") | |
| evidence_list = conn.execute("SELECT * FROM evidencevault WHERE projectid = ?", (projectid,)).fetchall() | |
| conn.close() | |
| if len(evidence_list) < 3: | |
| raise HTTPException(status_code=400, detail="INCOMPLETE PACK - FIX BEFORE EXPORT") | |
| forms = { | |
| "N1_Claim_Form": { | |
| "title": "Particulars of Claim", | |
| "breach_heads": [e["statutemapping"] for e in evidence_list], | |
| "exhibits": [e["exhibitid"] for e in evidence_list] | |
| }, | |
| "N244_Application": { | |
| "title": "Application Notice (Interim Relief)", | |
| "grounds": "Serious harm if interim relief not granted; risk of asset dissipation", | |
| "remedy_sought": "Mareva Freezing Injunction / Anton Piller Search Order" | |
| }, | |
| "EX160_Fee_Remission": { | |
| "title": "Application for Help with Court Fees", | |
| "disability_flag": True, | |
| "hardship_evidence": True | |
| } | |
| } | |
| return { | |
| "status": "Pack Ready", | |
| "projectid": projectid, | |
| "forms_generated": list(forms.keys()), | |
| "forms": forms, | |
| "signature": SIGNATURE | |
| } | |
| async def regulatory_shotgun(projectid: int): | |
| conn = get_db_connection() | |
| triggers = conn.execute( | |
| "SELECT DISTINCT regulator, breach_statute FROM regulatory_triggers WHERE projectid = ?", | |
| (projectid,) | |
| ).fetchall() | |
| if not triggers: | |
| conn.close() | |
| raise HTTPException(status_code=400, detail="No regulatory triggers identified") | |
| modules = { | |
| "Modular-FCA": { | |
| "target": "FCA / PRA", | |
| "breach": "PRIN 6 & BCOBS", | |
| "message": "Institutional reliance on vendor fraud; Treating Customers Fairly breach", | |
| "precedent": "FCA enforcement cases", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| }, | |
| "Modular-ICO": { | |
| "target": "ICO", | |
| "breach": "DPA 2018 s.45", | |
| "message": "Incomplete DSAR; adverse inference on missing call recordings", | |
| "precedent": "Gurieva v CSD", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| }, | |
| "Modular-SRA": { | |
| "target": "SRA / BSB", | |
| "breach": "Principles 2 & 5", | |
| "message": "Solicitor file distortion; misstatement of law", | |
| "precedent": "SRA enforcement decisions", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| }, | |
| "Modular-EHRC": { | |
| "target": "EHRC", | |
| "breach": "EqA 2010 s.20", | |
| "message": "Systematic disability discrimination; failure to adjust", | |
| "precedent": "Archibald v Fife", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| }, | |
| "Modular-Parliament": { | |
| "target": "Parliament", | |
| "breach": "Legislative gap", | |
| "message": "Systemic consumer protection failure", | |
| "precedent": "Legislative review", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| } | |
| } | |
| conn.close() | |
| return { | |
| "status": "Regulatory Shotgun Complete", | |
| "projectid": projectid, | |
| "modules": list(modules.keys()), | |
| "module_details": modules, | |
| "signature": SIGNATURE | |
| } | |
| async def calculate_damages(damages: DamagesInput): | |
| total = damages.general_damages + damages.aggravated_damages + damages.exemplary_damages | |
| opa_20_percent = total * 0.20 | |
| net_to_claimant = total - opa_20_percent | |
| ip_royalty = total * 0.10 | |
| conn = get_db_connection() | |
| conn.execute( | |
| """INSERT INTO damages_log | |
| (projectid, general_damages, aggravated_damages, exemplary_damages, | |
| total_damages, opa_participation) | |
| VALUES (?, ?, ?, ?, ?, ?)""", | |
| (damages.projectid, damages.general_damages, damages.aggravated_damages, | |
| damages.exemplary_damages, total, opa_20_percent) | |
| ) | |
| conn.commit() | |
| conn.close() | |
| return { | |
| "status": "Damages Calculated", | |
| "projectid": damages.projectid, | |
| "general_damages": damages.general_damages, | |
| "aggravated_damages": damages.aggravated_damages, | |
| "exemplary_damages": damages.exemplary_damages, | |
| "total_damages": total, | |
| "opa_participation_20percent": opa_20_percent, | |
| "net_to_claimant": net_to_claimant, | |
| "ip_royalty_10percent": ip_royalty, | |
| "signature": SIGNATURE | |
| } | |
| async def get_project_summary(projectid: int): | |
| conn = get_db_connection() | |
| project = conn.execute("SELECT * FROM projects WHERE id = ?", (projectid,)).fetchone() | |
| if not project: | |
| conn.close() | |
| raise HTTPException(status_code=404, detail="Project not found") | |
| evidence = conn.execute("SELECT COUNT(*) as count FROM evidencevault WHERE projectid = ?", (projectid,)).fetchone() | |
| audit_logs = conn.execute("SELECT * FROM auditlog WHERE projectid = ? ORDER BY timestamp DESC LIMIT 10", (projectid,)).fetchall() | |
| triggers = conn.execute("SELECT * FROM regulatory_triggers WHERE projectid = ?", (projectid,)).fetchall() | |
| damages = conn.execute("SELECT * FROM damages_log WHERE projectid = ? ORDER BY timestamp DESC LIMIT 1", (projectid,)).fetchone() | |
| conn.close() | |
| return { | |
| "project_id": projectid, | |
| "project_name": project["name"], | |
| "owner": project["owner"], | |
| "status": project["status"], | |
| "created": project["created_ts"], | |
| "evidence_count": evidence["count"], | |
| "audit_trail": [dict(log) for log in audit_logs], | |
| "regulatory_triggers": len(triggers), | |
| "triggers_detail": [dict(t) for t in triggers], | |
| "damages_calculated": dict(damages) if damages else None, | |
| "signature": SIGNATURE | |
| } | |
| async def framework_documentation(): | |
| return { | |
| "frameworks": [ | |
| "1. Ouroboros Temporal Cascade (1,440-loop daily cycle)", | |
| "2. Coding Demon (IP protection + cryptographic attribution)", | |
| "3. Mega Honey Badger Matrix (statutory breach mapping)", | |
| "4. Restless Honey Badger (evidence intake & hashing)", | |
| "5. Strategy Demon (Hurricane Stress Test)", | |
| "6. Regulatory Shotgun (multi-agency pressure)", | |
| "7. Ms.Nala Queen Nala (data ingestion pipeline)", | |
| "8. Beast Protocol (nuclear remedy deployment)", | |
| "9. Circular Logic Trap (pierce FOS immunity)", | |
| "10. Natalia Contradiction (disability discrimination)", | |
| "11. Piercing Immunity Matrix (4 statutory strategies)", | |
| "12. VIBES Cycle (6-hour operational rhythm)", | |
| "13. OPA Model (20% outcome participation)" | |
| ], | |
| "legal_weapons": [ | |
| "Hurricane Stress Test", | |
| "Fumbulance Maneuver", | |
| "Burden Flip Referral", | |
| "Electromagnet Checklist", | |
| "Dragonfly Eye Analysis", | |
| "Mareva + Anton Piller", | |
| "Hardship Fast-Track", | |
| "Qualified Privilege Defeat", | |
| "Circular Logic Trap", | |
| "Natalia Contradiction", | |
| "Regulatory Shotgun", | |
| "Evidence Spoliation Clock" | |
| ], | |
| "signature": SIGNATURE | |
| } | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host=HOST, port=PORT) | |
| import hashlib | |
| import sqlite3 | |
| import os | |
| from typing import List, Optional | |
| from fastapi import FastAPI, HTTPException, UploadFile, File | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel | |
| from PyPDF2 import PdfReader | |
| from gtts import gTTS | |
| import uvicorn | |
| from io import BytesIO | |
| import tempfile | |
| # ========================= | |
| # CONFIG | |
| # ========================= | |
| HOST = os.getenv("HOST", "0.0.0.0") | |
| PORT = int(os.getenv("PORT", "8000")) | |
| DB_PATH = os.getenv("DB_PATH", "ouroboros_datavault.db") | |
| OWNER = os.getenv("OWNER", "Dwayne Anthony Brian Galloway") | |
| SIGNATURE = os.getenv("SIGNATURE", "DABG-OUROBOROS-SIGNED") | |
| # ========================= | |
| # DATA MODELS | |
| # ========================= | |
| class FactEntry(BaseModel): | |
| date: str | |
| actor: str | |
| description: str | |
| evidenceid: Optional[str] = None | |
| class CaseProject(BaseModel): | |
| name: str | |
| facts: List[FactEntry] | |
| class DamagesInput(BaseModel): | |
| projectid: int | |
| general_damages: float | |
| aggravated_damages: float | |
| exemplary_damages: float | |
| # ========================= | |
| # FASTAPI APP | |
| # ========================= | |
| app = FastAPI( | |
| title="Ouroboros Decision Engine - 2026 Unified Build", | |
| description="Forensic litigation decision-support system powered by Honey Badger Protocol", | |
| version="2026.1.0-OUROBOROS" | |
| ) | |
| # ========================= | |
| # DATABASE | |
| # ========================= | |
| def get_db_connection(): | |
| conn = sqlite3.connect(DB_PATH) | |
| conn.row_factory = sqlite3.Row | |
| return conn | |
| def setup_vault(): | |
| conn = get_db_connection() | |
| conn.executescript(""" | |
| CREATE TABLE IF NOT EXISTS projects ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| name TEXT NOT NULL, | |
| owner TEXT DEFAULT 'Dwayne Anthony Brian Galloway', | |
| status TEXT DEFAULT 'Active', | |
| created_ts TEXT DEFAULT CURRENT_TIMESTAMP | |
| ); | |
| CREATE TABLE IF NOT EXISTS evidencevault ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER NOT NULL, | |
| factdate TEXT NOT NULL, | |
| actor TEXT NOT NULL, | |
| factdescription TEXT NOT NULL, | |
| statutemapping TEXT NOT NULL, | |
| evidencehash TEXT NOT NULL, | |
| exhibitid TEXT NOT NULL | |
| ); | |
| CREATE TABLE IF NOT EXISTS auditlog ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER NOT NULL, | |
| timestamp TEXT DEFAULT CURRENT_TIMESTAMP, | |
| action TEXT NOT NULL, | |
| integrityscore REAL, | |
| hashchain TEXT | |
| ); | |
| CREATE TABLE IF NOT EXISTS regulatory_triggers ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER NOT NULL, | |
| regulator TEXT NOT NULL, | |
| breach_statute TEXT NOT NULL, | |
| severity TEXT NOT NULL, | |
| hook_template TEXT NOT NULL | |
| ); | |
| CREATE TABLE IF NOT EXISTS damages_log ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER NOT NULL, | |
| general_damages REAL, | |
| aggravated_damages REAL, | |
| exemplary_damages REAL, | |
| total_damages REAL, | |
| opa_participation REAL, | |
| timestamp TEXT DEFAULT CURRENT_TIMESTAMP | |
| ); | |
| CREATE TABLE IF NOT EXISTS documents ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| projectid INTEGER, | |
| filename TEXT, | |
| extracted_text TEXT, | |
| audio_path TEXT, | |
| timestamp TEXT DEFAULT CURRENT_TIMESTAMP | |
| ); | |
| """) | |
| conn.commit() | |
| conn.close() | |
| # ========================= | |
| # STATUTORY BREACH MAPPING | |
| # ========================= | |
| def match_statute_breach(description: str) -> str: | |
| desc = description.lower() | |
| if any(k in desc for k in ["refund", "defect", "warranty", "fault", "brake", "faulty", "non-conforming"]): | |
| return "CRA 2015 s.19(14)" | |
| if any(k in desc for k in ["disability", "adjustment", "wheelchair", "adhd", "discrimination", "reasonable"]): | |
| return "EqA 2010 s.20/s.29" | |
| if any(k in desc for k in ["data", "sar", "dsar", "missing", "call recording", "deleted"]): | |
| return "DPA 2018 s.45/s.170" | |
| if any(k in desc for k in ["lie", "distort", "false", "misled", "fraud", "misrepresent"]): | |
| return "Fraud Act 2006 s.3/s.4" | |
| if any(k in desc for k in ["fca", "ombudsman", "fin", "regulated", "treating customers fairly", "prin"]): | |
| return "FSMA 2000 Sch.17/FCA PRIN 6" | |
| return "General Law (FCA PRIN)" | |
| # ========================= | |
| # DOCUMENT PROCESSOR | |
| # ========================= | |
| async def upload_documents(projectid: int = 0, case_name: str = "Document Intake", files: List[UploadFile] = File(...)): | |
| conn = get_db_connection() | |
| if projectid > 0: | |
| project = conn.execute("SELECT id FROM projects WHERE id = ?", (projectid,)).fetchone() | |
| if not project: | |
| conn.close() | |
| raise HTTPException(status_code=404, detail="Project not found") | |
| target_pid = projectid | |
| is_new = False | |
| else: | |
| cursor = conn.execute("INSERT INTO projects (name, owner) VALUES (?, ?)", (case_name, OWNER)) | |
| target_pid = cursor.lastrowid | |
| is_new = True | |
| hashchain = [] | |
| all_breaches = [] | |
| combined_text = "" | |
| file_results = [] | |
| for idx, upload_file in enumerate(files): | |
| filename = upload_file.filename | |
| ext = os.path.splitext(filename)[1].lower() | |
| extracted_text = "" | |
| try: | |
| content = await upload_file.read() | |
| if ext == ".pdf": | |
| reader = PdfReader(BytesIO(content)) | |
| for page in reader.pages: | |
| page_text = page.extract_text() | |
| if page_text: | |
| extracted_text += page_text + "\n" | |
| elif ext in [".txt", ".md", ".csv"]: | |
| extracted_text = content.decode("utf-8", errors="ignore") | |
| else: | |
| continue | |
| except Exception as e: | |
| file_results.append({"file": filename, "status": f"error: {str(e)}"}) | |
| continue | |
| if not extracted_text.strip(): | |
| file_results.append({"file": filename, "status": "no text extracted"}) | |
| continue | |
| combined_text += f"\n\n--- {filename} ---\n\n" + extracted_text | |
| statute = match_statute_breach(extracted_text) | |
| if statute != "General Law (FCA PRIN)": | |
| all_breaches.append({"file": filename, "statute": statute}) | |
| fact_string = f"2026-06-23|DOCUMENT|{filename}: {extracted_text[:800]}...|DOC-{idx+1}" | |
| fact_hash = hashlib.sha256(fact_string.encode("utf-8")).hexdigest() | |
| hashchain.append(fact_hash) | |
| conn.execute( | |
| """INSERT INTO evidencevault | |
| (projectid, factdate, actor, factdescription, statutemapping, evidencehash, exhibitid) | |
| VALUES (?, ?, ?, ?, ?, ?, ?)""", | |
| (target_pid, "2026-06-23", "DOCUMENT_PROCESSOR", f"{filename}: {extracted_text[:800]}...", statute, fact_hash, f"DOC-{target_pid}-{idx+1}") | |
| ) | |
| file_results.append({"file": filename, "status": "processed", "statute": statute, "chars": len(extracted_text)}) | |
| if hashchain: | |
| conn.execute( | |
| """INSERT INTO auditlog (projectid, action, integrityscore, hashchain) | |
| VALUES (?, ?, ?, ?)""", | |
| (target_pid, f"DOCUMENT_INTAKE_{len(hashchain)}_FILES", 1.0, "|".join(hashchain)) | |
| ) | |
| audio_path = None | |
| tts_text = combined_text[:3000] | |
| if tts_text.strip(): | |
| try: | |
| tts = gTTS(text=tts_text, lang="en", slow=False) | |
| tmp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3", dir="/tmp") | |
| tts.save(tmp_audio.name) | |
| audio_path = tmp_audio.name | |
| conn.execute("INSERT INTO documents (projectid, filename, extracted_text, audio_path) VALUES (?, ?, ?, ?)", | |
| (target_pid, "combined_tts", combined_text[:2000], audio_path)) | |
| except Exception: | |
| pass | |
| conn.commit() | |
| conn.close() | |
| return { | |
| "status": f"{'Created' if is_new else 'Added to'} Project {target_pid}", | |
| "projectid": target_pid, | |
| "files_processed": len(file_results), | |
| "file_results": file_results, | |
| "breaches_detected": len(all_breaches), | |
| "breaches": all_breaches, | |
| "audio_generated": audio_path is not None, | |
| "signature": SIGNATURE | |
| } | |
| async def get_audio(projectid: int): | |
| conn = get_db_connection() | |
| doc = conn.execute("SELECT audio_path FROM documents WHERE projectid = ? ORDER BY id DESC LIMIT 1", (projectid,)).fetchone() | |
| conn.close() | |
| if not doc or not doc["audio_path"]: | |
| raise HTTPException(status_code=404, detail="No audio found") | |
| return FileResponse(doc["audio_path"], media_type="audio/mpeg") | |
| # ========================= | |
| # CORE ENDPOINTS | |
| # ========================= | |
| async def root(): | |
| return {"system": "Ouroboros Litigation Station", "version": "2026.1.0-OUROBOROS", "docs": "/docs", "signature": SIGNATURE} | |
| async def health_check(): | |
| return { | |
| "status": "Operational", | |
| "system": "Ouroboros Decision Engine", | |
| "owner": OWNER, | |
| "version": "2026.1.0-OUROBOROS", | |
| "opa_rate": "20%", | |
| "ip_royalty": "10% (Coding Demon)", | |
| "signature": SIGNATURE | |
| } | |
| async def intake_evidence(case: CaseProject): | |
| conn = get_db_connection() | |
| cursor = conn.execute("INSERT INTO projects (name, owner) VALUES (?, ?)", (case.name, OWNER)) | |
| projectid = cursor.lastrowid | |
| hashchain = [] | |
| for fact in case.facts: | |
| fact_string = f"{fact.date}|{fact.actor}|{fact.description}|{fact.evidenceid or 'NONE'}" | |
| fact_hash = hashlib.sha256(fact_string.encode("utf-8")).hexdigest() | |
| hashchain.append(fact_hash) | |
| statute = match_statute_breach(fact.description) | |
| exhibit_id = fact.evidenceid or f"EX-{len(hashchain)}" | |
| conn.execute( | |
| """INSERT INTO evidencevault | |
| (projectid, factdate, actor, factdescription, statutemapping, evidencehash, exhibitid) | |
| VALUES (?, ?, ?, ?, ?, ?, ?)""", | |
| (projectid, fact.date, fact.actor, fact.description, statute, fact_hash, exhibit_id) | |
| ) | |
| conn.execute( | |
| """INSERT INTO auditlog (projectid, action, integrityscore, hashchain) | |
| VALUES (?, ?, ?, ?)""", | |
| (projectid, "INTAKE_RESTLESS", 1.0, "|".join(hashchain)) | |
| ) | |
| conn.commit() | |
| conn.close() | |
| return { | |
| "status": "Intake Complete", | |
| "projectid": projectid, | |
| "evidence_count": len(case.facts), | |
| "integrity": 1.0, | |
| "signature": SIGNATURE | |
| } | |
| async def run_temporal_cascade(projectid: int): | |
| conn = get_db_connection() | |
| evidence_rows = conn.execute("SELECT * FROM evidencevault WHERE projectid = ?", (projectid,)).fetchall() | |
| if not evidence_rows: | |
| conn.close() | |
| raise HTTPException(status_code=400, detail="No evidence found") | |
| regulatory_triggers = [] | |
| for evidence in evidence_rows: | |
| statute = evidence["statutemapping"] | |
| if "CRA" in statute: regulatory_triggers.append({"regulator": "FCA", "breach": statute}) | |
| if "EqA" in statute: regulatory_triggers.append({"regulator": "EHRC", "breach": statute}) | |
| if "DPA" in statute: regulatory_triggers.append({"regulator": "ICO", "breach": statute}) | |
| if "Fraud" in statute: regulatory_triggers.append({"regulator": "NCA", "breach": statute}) | |
| if "FSMA" in statute: regulatory_triggers.append({"regulator": "FCA", "breach": statute}) | |
| module_passes = 15 | |
| integrity_score = min(1.0, module_passes / 15) | |
| ownergate = "OPEN" if integrity_score >= 0.8 else "LOCKED" | |
| conn.execute( | |
| """INSERT INTO auditlog (projectid, action, integrityscore) | |
| VALUES (?, ?, ?)""", | |
| (projectid, "TEMPORAL_CASCADE_1440", integrity_score) | |
| ) | |
| for trigger in regulatory_triggers: | |
| conn.execute( | |
| """INSERT OR IGNORE INTO regulatory_triggers | |
| (projectid, regulator, breach_statute, severity, hook_template) | |
| VALUES (?, ?, ?, ?, ?)""", | |
| (projectid, trigger["regulator"], trigger["breach"], "HIGH", | |
| f"Complaint hook for {trigger['regulator']} - {trigger['breach']}") | |
| ) | |
| conn.commit() | |
| conn.close() | |
| return { | |
| "status": "Cascade Complete", | |
| "projectid": projectid, | |
| "integrity_score": integrity_score, | |
| "ownergate": ownergate, | |
| "regulatory_triggers": len(regulatory_triggers), | |
| "signature": SIGNATURE | |
| } | |
| async def generate_court_pack(projectid: int): | |
| conn = get_db_connection() | |
| project = conn.execute("SELECT * FROM projects WHERE id = ?", (projectid,)).fetchone() | |
| if not project: | |
| conn.close() | |
| raise HTTPException(status_code=404, detail="Project not found") | |
| evidence_list = conn.execute("SELECT * FROM evidencevault WHERE projectid = ?", (projectid,)).fetchall() | |
| conn.close() | |
| if len(evidence_list) < 3: | |
| raise HTTPException(status_code=400, detail="INCOMPLETE PACK - FIX BEFORE EXPORT") | |
| forms = { | |
| "N1_Claim_Form": { | |
| "title": "Particulars of Claim", | |
| "breach_heads": [e["statutemapping"] for e in evidence_list], | |
| "exhibits": [e["exhibitid"] for e in evidence_list] | |
| }, | |
| "N244_Application": { | |
| "title": "Application Notice (Interim Relief)", | |
| "grounds": "Serious harm if interim relief not granted; risk of asset dissipation", | |
| "remedy_sought": "Mareva Freezing Injunction / Anton Piller Search Order" | |
| }, | |
| "EX160_Fee_Remission": { | |
| "title": "Application for Help with Court Fees", | |
| "disability_flag": True, | |
| "hardship_evidence": True | |
| } | |
| } | |
| return { | |
| "status": "Pack Ready", | |
| "projectid": projectid, | |
| "forms_generated": list(forms.keys()), | |
| "forms": forms, | |
| "signature": SIGNATURE | |
| } | |
| async def regulatory_shotgun(projectid: int): | |
| conn = get_db_connection() | |
| triggers = conn.execute( | |
| "SELECT DISTINCT regulator, breach_statute FROM regulatory_triggers WHERE projectid = ?", | |
| (projectid,) | |
| ).fetchall() | |
| if not triggers: | |
| conn.close() | |
| raise HTTPException(status_code=400, detail="No regulatory triggers identified") | |
| modules = { | |
| "Modular-FCA": { | |
| "target": "FCA / PRA", | |
| "breach": "PRIN 6 & BCOBS", | |
| "message": "Institutional reliance on vendor fraud; Treating Customers Fairly breach", | |
| "precedent": "FCA enforcement cases", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| }, | |
| "Modular-ICO": { | |
| "target": "ICO", | |
| "breach": "DPA 2018 s.45", | |
| "message": "Incomplete DSAR; adverse inference on missing call recordings", | |
| "precedent": "Gurieva v CSD", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| }, | |
| "Modular-SRA": { | |
| "target": "SRA / BSB", | |
| "breach": "Principles 2 & 5", | |
| "message": "Solicitor file distortion; misstatement of law", | |
| "precedent": "SRA enforcement decisions", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| }, | |
| "Modular-EHRC": { | |
| "target": "EHRC", | |
| "breach": "EqA 2010 s.20", | |
| "message": "Systematic disability discrimination; failure to adjust", | |
| "precedent": "Archibald v Fife", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| }, | |
| "Modular-Parliament": { | |
| "target": "Parliament", | |
| "breach": "Legislative gap", | |
| "message": "Systemic consumer protection failure", | |
| "precedent": "Legislative review", | |
| "registers": ["Plain English", "QC Forensic", "Parliamentary"] | |
| } | |
| } | |
| conn.close() | |
| return { | |
| "status": "Regulatory Shotgun Complete", | |
| "projectid": projectid, | |
| "modules": list(modules.keys()), | |
| "module_details": modules, | |
| "signature": SIGNATURE | |
| } | |
| async def calculate_damages(damages: DamagesInput): | |
| total = damages.general_damages + damages.aggravated_damages + damages.exemplary_damages | |
| opa_20_percent = total * 0.20 | |
| net_to_claimant = total - opa_20_percent | |
| ip_royalty = total * 0.10 | |
| conn = get_db_connection() | |
| conn.execute( | |
| """INSERT INTO damages_log | |
| (projectid, general_damages, aggravated_damages, exemplary_damages, | |
| total_damages, opa_participation) | |
| VALUES (?, ?, ?, ?, ?, ?)""", | |
| (damages.projectid, damages.general_damages, damages.aggravated_damages, | |
| damages.exemplary_damages, total, opa_20_percent) | |
| ) | |
| conn.commit() | |
| conn.close() | |
| return { | |
| "status": "Damages Calculated", | |
| "projectid": damages.projectid, | |
| "general_damages": damages.general_damages, | |
| "aggravated_damages": damages.aggravated_damages, | |
| "exemplary_damages": damages.exemplary_damages, | |
| "total_damages": total, | |
| "opa_participation_20percent": opa_20_percent, | |
| "net_to_claimant": net_to_claimant, | |
| "ip_royalty_10percent": ip_royalty, | |
| "signature": SIGNATURE | |
| } | |
| async def get_project_summary(projectid: int): | |
| conn = get_db_connection() | |
| project = conn.execute("SELECT * FROM projects WHERE id = ?", (projectid,)).fetchone() | |
| if not project: | |
| conn.close() | |
| raise HTTPException(status_code=404, detail="Project not found") | |
| evidence = conn.execute("SELECT COUNT(*) as count FROM evidencevault WHERE projectid = ?", (projectid,)).fetchone() | |
| audit_logs = conn.execute("SELECT * FROM auditlog WHERE projectid = ? ORDER BY timestamp DESC LIMIT 10", (projectid,)).fetchall() | |
| triggers = conn.execute("SELECT * FROM regulatory_triggers WHERE projectid = ?", (projectid,)).fetchall() | |
| damages = conn.execute("SELECT * FROM damages_log WHERE projectid = ? ORDER BY timestamp DESC LIMIT 1", (projectid,)).fetchone() | |
| conn.close() | |
| return { | |
| "project_id": projectid, | |
| "project_name": project["name"], | |
| "owner": project["owner"], | |
| "status": project["status"], | |
| "created": project["created_ts"], | |
| "evidence_count": evidence["count"], | |
| "audit_trail": [dict(log) for log in audit_logs], | |
| "regulatory_triggers": len(triggers), | |
| "triggers_detail": [dict(t) for t in triggers], | |
| "damages_calculated": dict(damages) if damages else None, | |
| "signature": SIGNATURE | |
| } | |
| async def framework_documentation(): | |
| return { | |
| "frameworks": [ | |
| "1. Ouroboros Temporal Cascade (1,440-loop daily cycle)", | |
| "2. Coding Demon (IP protection + cryptographic attribution)", | |
| "3. Mega Honey Badger Matrix (statutory breach mapping)", | |
| "4. Restless Honey Badger (evidence intake & hashing)", | |
| "5. Strategy Demon (Hurricane Stress Test)", | |
| "6. Regulatory Shotgun (multi-agency pressure)", | |
| "7. Ms.Nala Queen Nala (data ingestion pipeline)", | |
| "8. Beast Protocol (nuclear remedy deployment)", | |
| "9. Circular Logic Trap (pierce FOS immunity)", | |
| "10. Natalia Contradiction (disability discrimination)", | |
| "11. Piercing Immunity Matrix (4 statutory strategies)", | |
| "12. VIBES Cycle (6-hour operational rhythm)", | |
| "13. OPA Model (20% outcome participation)" | |
| ], | |
| "legal_weapons": [ | |
| "Hurricane Stress Test", | |
| "Fumbulance Maneuver", | |
| "Burden Flip Referral", | |
| "Electromagnet Checklist", | |
| "Dragonfly Eye Analysis", | |
| "Mareva + Anton Piller", | |
| "Hardship Fast-Track", | |
| "Qualified Privilege Defeat", | |
| "Circular Logic Trap", | |
| "Natalia Contradiction", | |
| "Regulatory Shotgun", | |
| "Evidence Spoliation Clock" | |
| ], | |
| "signature": SIGNATURE | |
| } | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host=HOST, port=PORT) | |