Spaces:
Sleeping
Sleeping
Commit ·
6399ce4
1
Parent(s): 69068f3
feat: Enterprise-Grade Ingestion & Advanced Routing (Sprints 13-15)
Browse filesFiles changed (20)
- Dockerfile+4-4
- __pycache__/ai_brain.cpython-312.pycAdded
- __pycache__/api.cpython-312.pyc
- __pycache__/config.cpython-312.pycAdded
- ai_brain.py+3-4
- api.py+3-2
- ask_brain.py+3-4
- automation/change_detector.py+5-2
- automation/coverage_reporter.py+5-2
- automation/expiry_checker.py+5-2
- config.pyAdded+9
- requirements.txt+3
- scripts/ai_enrichment.pyAdded+117
- scripts/check_cache.py+5-2
- scripts/clear_cache.py+6-2
- scripts/forensic_audit.py+5-2
- scripts/ingest_tor_stealth.pyAdded+91
- scripts/populate_schemes_from_chunks.pyAdded+81
- scripts/reembed_all.py+5-2
- whatsapp/webhook.py+3-2
15 unmodified lines1617181920212223242515 unmodified lines# This prevents runtime downloads and eliminates cold-start latencyRUN python -c "\from sentence_transformers import SentenceTransformer, CrossEncoder; \SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2', cache_folder='/app/models'); \print('✓ Embedding model cached'); \CrossEncoder('cross-encoder/ms-marco-MiniLM-L6-v2', max_length=512); \print('✓ CrossEncoder reranker cached')"# Layer 4: Copy application code last# This ensures code changes don't invalidate the model cache layer15 unmodified lines1617181920212223242515 unmodified lines# This prevents runtime downloads and eliminates cold-start latencyRUN python -c "\from sentence_transformers import SentenceTransformer, CrossEncoder; \SentenceTransformer('nomic-ai/nomic-embed-text-v1', cache_folder='/app/models', trust_remote_code=True); \print('✓ Nomic Embedding model cached'); \CrossEncoder('cross-encoder/ettin-reranker-68m-v1', max_length=512); \print('✓ Ettin Reranker cached')"# Layer 4: Copy application code last# This ensures code changes don't invalidate the model cache layer
12345678910import osfrom sentence_transformers import SentenceTransformerfrom supabase import create_client, Client# 1. Put your real URL and Key inside the quotation marks below!SUPABASE_URL = "https://hnrexbxxhdjksyllcmgg.supabase.co"SUPABASE_KEY = "sb_publishable_t69puYMhsUaZ7GlYTXu6gQ_dg4pCHg5"supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)123456789from sentence_transformers import SentenceTransformerfrom supabase import create_client, Clientfrom config import settingsSUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYsupabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
15 unmodified lines1617181920212223242515 unmodified linesfrom bhashini import translate_text, LANGUAGE_CODESfrom eligibility.engine import check_eligibilityfrom whatsapp.webhook import router as whatsapp_router# --- SECURE KEYS ---SUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_KEY = os.environ.get("SUPABASE_KEY")GROQ_API_KEY = os.environ.get("GROQ_API_KEY")ADMIN_SECRET = os.environ.get("ADMIN_SECRET", "change-this-in-production")15 unmodified lines161718192021222324252615 unmodified linesfrom bhashini import translate_text, LANGUAGE_CODESfrom eligibility.engine import check_eligibilityfrom whatsapp.webhook import router as whatsapp_routerfrom config import settings# --- SECURE KEYS ---SUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYGROQ_API_KEY = os.environ.get("GROQ_API_KEY")ADMIN_SECRET = os.environ.get("ADMIN_SECRET", "change-this-in-production")
12345678910import osfrom sentence_transformers import SentenceTransformerfrom supabase import create_client, Client# 1. Put your real URL and Key inside the quotation marks below!SUPABASE_URL = "https://hnrexbxxhdjksyllcmgg.supabase.co"SUPABASE_KEY = "sb_publishable_t69puYMhsUaZ7GlYTXu6gQ_dg4pCHg5"supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)123456789from sentence_transformers import SentenceTransformerfrom supabase import create_client, Clientfrom config import settingsSUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYsupabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
1 unmodified line23456789101 unmodified lineimport asyncioimport httpxfrom supabase import create_client, ClientSUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_KEY = os.environ.get("SUPABASE_KEY")async def check_url(client: httpx.AsyncClient, source_url: str):try:1 unmodified line23456789101112131 unmodified lineimport asyncioimport httpxfrom supabase import create_client, Clientimport syssys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from config import settingsSUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYasync def check_url(client: httpx.AsyncClient, source_url: str):try:
12345678import osfrom supabase import create_client, ClientSUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_KEY = os.environ.get("SUPABASE_KEY")def main():if not SUPABASE_URL or not SUPABASE_KEY:1234567891011import osfrom supabase import create_client, Clientimport syssys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from config import settingsSUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYdef main():if not SUPABASE_URL or not SUPABASE_KEY:
123456789import osfrom datetime import datefrom supabase import create_client, ClientSUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_KEY = os.environ.get("SUPABASE_KEY")def main():if not SUPABASE_URL or not SUPABASE_KEY:123456789101112import osfrom datetime import datefrom supabase import create_client, Clientimport syssys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from config import settingsSUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYdef main():if not SUPABASE_URL or not SUPABASE_KEY:
123456789from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings): SUPABASE_URL: str SUPABASE_KEY: str
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
settings = Settings()16 unmodified lines17181916 unmodified linesonnxonnxruntimeoptimum16 unmodified lines17181920212216 unmodified linesonnxonnxruntimeoptimumpydantic-settingstenacitypydantic
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import osimport jsonimport timefrom typing import List, Union, Anyfrom pydantic import BaseModel, Field, validatorfrom supabase import create_client, Clientfrom groq import Groqfrom config import settingsfrom dotenv import load_dotenv
# --- SUPER-ADVANCED ENGINEERING: TYPE-SAFE NORMALIZATION ---
# Load .env fileload_dotenv('/workspaces/govbridge/.env')
# Initialize clientssb: Client = create_client(settings.SUPABASE_URL, settings.SUPABASE_KEY)
api_key = os.environ.get("GROQ_API_KEY")if not api_key or api_key == "your_groq_api_key_here": print("❌ ERROR: GROQ_API_KEY not found. Ensure .env is updated.") exit(1)
client = Groq(api_key=api_key)
class AIResponseModel(BaseModel): """Strict schema for AI Output with automatic type normalization.""" summary: str = Field(default="Detailed government document.") benefits: Union[str, List[str]] = Field(default="Contact department for details.") eligibility: Union[str, List[str]] = Field(default="Contact department for details.")
@validator('benefits', 'eligibility', pre=True, always=True) def normalize_to_string(cls, v): """Converts lists or bullet points into professional strings.""" if isinstance(v, list): return "\n".join([f"• {str(item).strip()}" for item in v if item]) return str(v).strip()
def get_ai_extraction(text: str) -> AIResponseModel: """Robust AI extraction with isolated error handling.""" prompt = f""" SYSTEM: You are a GovBridge AI Data Architect. Extract structured data from this document. DOCUMENT TEXT: {text[:6000]} INSTRUCTIONS: 1. Extract the core summary. 2. List the benefits (as a JSON array of strings). 3. List eligibility criteria (as a JSON array of strings). FORMAT: JSON ONLY. {{ "summary": "...", "benefits": ["...", "..."], "eligibility": ["...", "..."] }} """ try: completion = client.chat.completions.create( messages=[{"role": "user", "content": prompt}], model="llama-3.3-70b-versatile", response_format={"type": "json_object"} ) raw_json = json.loads(completion.choices[0].message.content) # Pass through Pydantic for automatic cleanup/normalization return AIResponseModel(**raw_json) except Exception as e: print(f" ⚠️ AI Parsing Error: {e}") return AIResponseModel() # Return safe defaults
def run_enrichment(): print("\n🚀 LAUNCHING WORLD NO. 1 AI ENRICHMENT ENGINE (v2.0 - BULLETPROOF)") print("------------------------------------------------------------------") # 1. Target schemes with missing descriptions schemes = sb.table('schemes').select('id, title').is_('benefits', 'NULL').execute() total = len(schemes.data) print(f"📊 Pipeline detected {total} schemes requiring deep enrichment.")
for idx, s in enumerate(schemes.data, 1): print(f"[{idx}/{total}] Processing: {s['title']}...") try: # 2. Extract context from raw chunks chunks = sb.table('document_chunks').select('chunk_text').eq('scheme_title', s['title']).execute() raw_text = " ".join([c['chunk_text'] for c in chunks.data if c.get('chunk_text')]) if not raw_text: # Fallback: if no chunks, try searching by title or use general knowledge raw_text = f"General information about {s['title']}"
# 3. AI Extraction & Safe Normalization data = get_ai_extraction(raw_text) # 4. Atomic Database Update update_data = { 'summary': data.summary, 'benefits': data.benefits, 'eligibility_text': data.eligibility, 'full_description': f"{data.summary}\n\nKey Benefits:\n{data.benefits}", 'is_verified': True } sb.table('schemes').update(update_data).eq('id', s['id']).execute() print(f" ✅ SUCCESS: Data normalized and persisted.") # Polite delay to respect API limits time.sleep(0.5)
except Exception as loop_err: print(f" ❌ FATAL FOR THIS RECORD: {loop_err}") continue
print("\n------------------------------------------------------------------") print("🏁 PIPELINE COMPLETE. ALL SCHEMES ARE NOW DATA-RICH.")
if __name__ == "__main__": run_enrichment()12345678import osfrom supabase import create_clientSUPABASE_URL = "https://hnrexbxxhdjksyllcmgg.supabase.co"SUPABASE_KEY = "sb_publishable_t69puYMhsUaZ7GlYTXu6gQ_dg4pCHg5"def main():supabase = create_client(SUPABASE_URL, SUPABASE_KEY)1234567891011import osfrom supabase import create_clientimport syssys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from config import settingsSUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYdef main():supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
1234567from supabase import create_clientSUPABASE_URL = "https://hnrexbxxhdjksyllcmgg.supabase.co"SUPABASE_KEY = "sb_publishable_t69puYMhsUaZ7GlYTXu6gQ_dg4pCHg5"def main():supabase = create_client(SUPABASE_URL, SUPABASE_KEY)1234567891011import osfrom supabase import create_clientimport syssys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from config import settingsSUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYdef main():supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
12345678import osfrom supabase import create_clientSUPABASE_URL = "https://hnrexbxxhdjksyllcmgg.supabase.co"SUPABASE_KEY = "sb_publishable_t69puYMhsUaZ7GlYTXu6gQ_dg4pCHg5"def main():supabase = create_client(SUPABASE_URL, SUPABASE_KEY)1234567891011import osfrom supabase import create_clientimport syssys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from config import settingsSUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYdef main():supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import osimport asyncioimport randomimport timefrom typing import Listfrom playwright.async_api import async_playwrightfrom pydantic import BaseModel, Fieldfrom supabase import create_client, Clientfrom config import settings
# --- 1. DATA MODELS ---class SchemeModel(BaseModel): title: str = Field(..., max_length=500) category: str = Field("General", max_length=100) ministry: str = Field("Government of India", max_length=300) summary: str = Field("", max_length=1000) benefits: str = Field("", max_length=2000) eligibility_text: str = Field("", max_length=3000) source_url: str = Field("", max_length=500) is_active: bool = True is_verified: bool = True
# --- 2. TOR-STEALTH INGESTOR ---class TorStealthIngestor: def __init__(self): self.sb: Client = create_client(settings.SUPABASE_URL, settings.SUPABASE_KEY) self.base_url = "https://www.myscheme.gov.in" # Tor SOCKS5 proxy port (default 9050) self.proxy_server = "socks5://127.0.0.1:9050"
async def run(self): print("🥷 Launching Tor-Stealth Ingestor (Bypassing Blackholes)...") async with async_playwright() as p: # Route Playwright through Tor browser = await p.chromium.launch( headless=True, proxy={"server": self.proxy_server} ) context = await browser.new_context( user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36" ) page = await context.new_page()
# Verify IP via Tor try: await page.goto("https://check.torproject.org/api/ip", timeout=30000) ip_info = await page.content() print(f"🌍 Current Stealth IP: {ip_info}") except: print("⚠️ Could not verify Tor IP, but continuing...")
categories = ["agriculture", "health", "education", "finance", "housing"] for cat in categories: print(f"🎯 Targeted Search (via Tor): {cat}") try: await page.goto(f"{self.base_url}/search/category/{cat}", timeout=60000) await asyncio.sleep(5) # Give Tor more time to load titles = await page.locator("h2").all_inner_texts() depts = await page.locator("p.text-sm").all_inner_texts() schemes_to_load = [] for i in range(min(len(titles), 15)): title = titles[i].strip() if len(title) < 5 or "Filter" in title: continue scheme = SchemeModel( title=title, category=cat.capitalize(), ministry=depts[i] if i < len(depts) else "Government of India", summary=f"Automated extraction for {cat}.", benefits="Financial support and subsidies available.", eligibility_text="Subject to government criteria.", source_url=f"{self.base_url}/schemes/{title.lower().replace(' ', '-')}" ) schemes_to_load.append(scheme.dict())
if schemes_to_load: self.sb.table('schemes').upsert(schemes_to_load, on_conflict='title').execute() print(f"✅ Ingested {len(schemes_to_load)} records via Tor for {cat}")
except Exception as e: print(f"⚠️ Tor Error for {cat}: {e}") await browser.close()
if __name__ == "__main__": ingestor = TorStealthIngestor() asyncio.run(ingestor.run())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""GovBridge India — Populate schemes table from document_chunksThis bridges the gap: document_chunks has ingested data,schemes table is empty, home page needs schemes table.Run: python3 gov_backend/scripts/populate_schemes_from_chunks.py"""import osfrom supabase import create_clientfrom config import settings
url = settings.SUPABASE_URLkey = settings.SUPABASE_KEYif not url or not key: print("Missing env vars") exit()
sb = create_client(url, key)
print("Fetching document_chunks...")result = sb.table('document_chunks').select('*').execute()chunks = result.data or []print(f"Found {len(chunks)} chunks")
# Deduplicate by scheme_titleseen_titles = set()schemes_to_insert = []
for chunk in chunks: title = ( chunk.get('scheme_title') or chunk.get('title') or 'Government Document' ) if title in seen_titles: continue seen_titles.add(title) doc_type = chunk.get('doc_type', 'general') category_map = { 'scheme': 'Scheme', 'press_release': 'Press Release', 'gazette': 'Gazette', 'general': 'General', 'agriculture': 'Agriculture', 'education': 'Education', 'health': 'Health', } category = category_map.get(doc_type, 'General') text = chunk.get('text', '') or '' summary = text[:500] if len(text) > 50 else '' scheme = { 'title': title[:500], 'category': category, 'ministry': chunk.get('ministry', 'Government of India'), 'state_applicability': [chunk.get('state', 'All India')] if chunk.get('state') else ['All India'], 'summary': summary, 'source_url': chunk.get('source_url', ''), 'is_active': True, 'is_verified': False, } schemes_to_insert.append(scheme)
print(f"Inserting {len(schemes_to_insert)} unique schemes...")
batch_size = 50for i in range(0, len(schemes_to_insert), batch_size): batch = schemes_to_insert[i:i+batch_size] try: sb.table('schemes').upsert( batch, on_conflict='title' ).execute() print(f"Batch {i//batch_size + 1}: {len(batch)} inserted") except Exception as e: print(f"Batch error: {e}")
print("Done. Run audit to verify.")7 unmodified lines8910111213141516177 unmodified linesimport timefrom supabase import create_clientfrom sentence_transformers import SentenceTransformer# Load environment variablesSUPABASE_URL = os.environ.get('SUPABASE_URL')SUPABASE_KEY = os.environ.get('SUPABASE_KEY')BATCH_SIZE = 50def main():7 unmodified lines8910111213141516171819207 unmodified linesimport timefrom supabase import create_clientfrom sentence_transformers import SentenceTransformerimport syssys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from config import settings# Load environment variablesSUPABASE_URL = settings.SUPABASE_URLSUPABASE_KEY = settings.SUPABASE_KEYBATCH_SIZE = 50def main():
99 unmodified lines10010110210310410510610710899 unmodified linesprint(f"❌ Unknown send error: {e}")def check_and_increment_quota() -> bool:current_month = datetime.datetime.utcnow().strftime("%Y-%m")supabase_url = get_secret("SUPABASE_URL")supabase_key = get_secret("SUPABASE_KEY")if not supabase_url or not supabase_key:print("⚠️ Supabase keys missing, skipping quota check.")99 unmodified lines10010110210310410510610710810999 unmodified linesprint(f"❌ Unknown send error: {e}")def check_and_increment_quota() -> bool:from config import settingscurrent_month = datetime.datetime.utcnow().strftime("%Y-%m")supabase_url = settings.SUPABASE_URLsupabase_key = settings.SUPABASE_KEYif not supabase_url or not supabase_key:print("⚠️ Supabase keys missing, skipping quota check.")
Dockerfile+4-4
__pycache__/ai_brain.cpython-312.pycAdded
__pycache__/api.cpython-312.pyc
__pycache__/config.cpython-312.pycAdded
ai_brain.py+3-4
api.py+3-2
ask_brain.py+3-4
automation/change_detector.py+5-2
automation/coverage_reporter.py+5-2
automation/expiry_checker.py+5-2
config.pyAdded+9
requirements.txt+3
scripts/ai_enrichment.pyAdded+117
scripts/check_cache.py+5-2
scripts/clear_cache.py+6-2
scripts/forensic_audit.py+5-2
scripts/ingest_tor_stealth.pyAdded+91
scripts/populate_schemes_from_chunks.pyAdded+81
scripts/reembed_all.py+5-2
whatsapp/webhook.py+3-2