rmi-backend/app/_archive/legacy_2026_07/ai_pipeline2.py
cryptorugmunch 628c1d2a10
Some checks failed
CI / build (push) Failing after 3s
refactor(rmi-backend,audit): mount Wave 3 + archive 136 dead-code files (P2.3)
PHASE 2.3 (AUDIT-2026-Q3.md):

Task 1 — Wire-in Wave 3 (1 router mounted, 2 deferred):
  - app.routers.unified_scanner_router mounted at /api/v2/scanner/* (2 routes:
    POST /api/v2/scanner/token/scan, POST /api/v2/scanner/wallet/scan).
    Refactored prefix from /api/v2 -> /api/v2/scanner to avoid future conflicts
    with the v1 /api/v1/scanner/ stub.
  - app.routers.unified_wallet_scanner DEFERRED (no router APIRouter attribute;
    library module consumed by unified_scanner_router via get_wallet_scanner()).
  - app.routers.admin_extensions DEFERRED (DORMANT per audit; 25 routes at
    /api/v1/admin/* would shadow /api/v1/admin/alerts_webhook).

Task 2 — Archive 136 dead-code files to app/_archive/legacy_2026_07/:
  - 73 routers in app/routers/ (reach graph showed zero reach into mount.py).
  - 63 flat app/*.py (domain modules never imported by live code).
  - 1 file RESTORED post-archive: app/routers/x402_bridge_health.py (caught by
    tests/unit/test_bridge_health.py which directly imports it; reach graph
    considered tests/ only as transitive reach — to be patched in next cycle).

Forced-LIVE (NOT archived per user directive):
  - app/ai_pipeline_v3.py  (3 importers in audit window, importers themselves DEAD)
  - app/splade_bm25.py       (LIVE via app.rag_service)
  - app/wallet_manager_v2.py (LIVE via x402_enforcement, x402_tools, sweep_all, sweep_now)
  - app/crypto_embeddings.py (NOT in audit ARCHIVE list; heavy import graph)

Verification (forward-import closure from mount.py + main.py + factory.py + lifespan.py):
  - imports = 348 app.* modules
  - reached = 194 files reachable from roots
  - archive set = audit_dead (186) - reached - forced_live (4) - test_live (1) = 136
  - Net delta: 136 files moved, 44,932 LOC reduction, 293->295 active routes (+2 from Wave 3)

pyproject.toml updates:
  - setuptools.packages.find: added exclude for app._archive*
  - ruff.extend-exclude: added "app/_archive/"
  - mypy.exclude: added "app/_archive/"

Smoke test: pytest tests/ — 817 passed, 3 pre-existing failures unchanged
(0 new failures; 0 routes lost; all 4 forced-LIVE files still importable).

Restoration: git mv app/_archive/legacy_2026_07/<name>.py <original-path>
and add the import to app/mount.py ROUTER_MODULES.

Refs: AUDIT-2026-Q3.md /home/dev/pry/rmi-final-deadcode-2026-07-06.md
2026-07-06 20:52:31 +02:00

113 lines
4.1 KiB
Python

#!/usr/bin/env python3
"""
RMI AI Pipeline Part 2 - Remaining 7 Modules
=============================================
Community Forensics | Cross-Chain Entity | Ghost Blog | Social Media | Token Compare
All Ollama Cloud deepseek-v4-flash. ~$0.001/operation.
"""
import json
import logging
import os
from urllib.request import Request, urlopen
logger = logging.getLogger("rmi.ai_pipeline2")
OLLAMA_KEY = os.getenv("OLLAMA_API_KEY", os.getenv("DEEPSEEK_API_KEY", ""))
OLLAMA_URL = "https://ollama.com/v1/chat/completions"
MODEL = "deepseek-v4-flash"
def _call_ai(system: str, prompt: str, max_tokens: int = 250, temp: float = 0.3) -> str:
try:
body = json.dumps(
{
"model": MODEL,
"messages": [
{"role": "system", "content": system},
{"role": "user", "content": prompt},
],
"max_tokens": max_tokens,
"temperature": temp,
}
).encode()
req = Request(
OLLAMA_URL,
data=body,
headers={"Authorization": f"Bearer {OLLAMA_KEY}", "Content-Type": "application/json"},
)
resp = urlopen(req, timeout=15)
return json.loads(resp.read())["choices"][0]["message"]["content"].strip()
except Exception as e:
logger.error(f"AI call failed: {e}")
return ""
# ── 8. COMMUNITY FORENSICS AUTO-ANALYSIS ──
FORENSICS_SYSTEM = """You are a crypto forensics investigator. A community member submitted a suspicious token for review.
Analyze the information and provide:
1. Initial verdict (LIKELY SCAM / SUSPICIOUS / NEEDS MORE INFO)
2. Key concerns (2-3 bullet points)
3. Recommended next steps for the investigator
Keep it under 150 words."""
def analyze_community_submission(submission: dict) -> str:
return _call_ai(FORENSICS_SYSTEM, json.dumps(submission)[:1500], max_tokens=250)
# ── 10. CROSS-CHAIN ENTITY DETECTION ──
CROSSCHAIN_SYSTEM = """You identify crypto entities operating across multiple blockchains.
Given wallet data from different chains, determine if they're the same entity.
Reply format: MATCH|confidence_0-100|reason OR NO_MATCH|reason"""
def detect_cross_chain(wallets: dict) -> str:
return _call_ai(CROSSCHAIN_SYSTEM, json.dumps(wallets)[:1500], max_tokens=100)
# ── 11. GHOST BLOG AUTO-DRAFT ──
GHOST_SYSTEM = """You are a crypto security blogger for Rug Munch Intelligence (rugmunch.io).
Write a blog post draft from scanner data and incident reports.
Structure:
- Title (catchy, SEO-friendly, under 80 chars)
- Hook (1 sentence that grabs attention)
- Body (3-4 paragraphs explaining the threat)
- Key takeaways (2-3 bullet points)
- Call to action (check your tokens, use our scanner)
Use markdown formatting. Professional but engaging tone."""
def draft_blog_post(topic: str, data: dict) -> str:
prompt = f"Topic: {topic}\n\nData:\n{json.dumps(data)[:2000]}"
return _call_ai(GHOST_SYSTEM, prompt, max_tokens=500, temp=0.6)
# ── 13. SOCIAL MEDIA POST GENERATOR ──
SOCIAL_SYSTEM = """You are the social media manager for Rug Munch Intelligence (@CryptoRugMunch).
Write a tweet/telegram post about a crypto security finding.
Rules:
- Under 280 chars for Twitter, under 500 for Telegram
- Start with a hook (stat, warning, or question)
- Include $TICKER if relevant
- End with a call to action or link
- Use emojis sparingly (1-2 max)
- No hashtag spam (2-3 max)
Reply format: TWITTER: <tweet> | TELEGRAM: <post>"""
def generate_social_post(incident: dict, platform: str = "both") -> str:
return _call_ai(SOCIAL_SYSTEM, json.dumps(incident)[:1000], max_tokens=200, temp=0.7)
# ── 14. TOKEN COMPARISON ENGINE ──
COMPARE_SYSTEM = """Compare two crypto tokens for safety. Given their scanner results, determine which is safer and why.
Reply format:
SAFER: <token_name>
REASON: <2-3 sentence comparison>
SCORE_DIFF: <token1_score> vs <token2_score>
KEY_DIFFERENCES: <bullet points>"""
def compare_tokens(token_a: dict, token_b: dict) -> str:
prompt = f"Token A:\n{json.dumps(token_a)[:800]}\n\nToken B:\n{json.dumps(token_b)[:800]}"
return _call_ai(COMPARE_SYSTEM, prompt, max_tokens=200)