Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492501 unmodified line2522532542552562572582592602612622632642652664 unmodified lines2712722732742752762772782793 unmodified lines2832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933942 unmodified lines3973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065071 unmodified line5095105115125135145155165175185195205215225235245255265275285295305315325335345355365375381 unmodified line540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761# ============================================================================# 1. CONSOLIDATED IMPORTS# ============================================================================import gradio as grimport sqlite3import pandas as pdfrom huggingface_hub import hf_hub_download, HfApifrom fastapi import FastAPI, Responsefrom fastapi.responses import JSONResponseimport osimport timeimport jsonfrom typing import Optional, Dict, List, Anyimport uvicornimport tracebackfrom pathlib import Pathfrom contextlib import asynccontextmanager # <-- FIX 1: Add this import# ============================================================================# 2. SHARED GLOBALS & CONFIGURATION# ============================================================================# --- Languages ---TARGET_LANGUAGES = ['de', 'en', 'es', 'fr', 'it', 'ja', 'nl', 'pl', 'pt', 'ru', 'zh']print(f"π Target Languages: {', '.join([l.upper() for l in TARGET_LANGUAGES])}")# --- Hugging Face & DB Config ---INDEXED_REPO_ID = "cstr/conceptnet-de-indexed"INDEXED_DB_FILENAME = "conceptnet-de-indexed.db"PROGRESS_FILENAME = "indexing_progress.json"CONCEPTNET_BASE_URI = "http://conceptnet.io"DB_PATH: Optional[str] = None # Will be set by setup_database()# --- HF Token ---HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN") or os.environ.get("HF_API_TOKEN")# --- All relations MUST be full URLs ---CONCEPTNET_RELATIONS: Dict[str, str] = {"RelatedTo": f"{CONCEPTNET_BASE_URI}/r/RelatedTo","IsA": f"{CONCEPTNET_BASE_URI}/r/IsA","PartOf": f"{CONCEPTNET_BASE_URI}/r/PartOf","HasA": f"{CONCEPTNET_BASE_URI}/r/HasA","UsedFor": f"{CONCEPTNET_BASE_URI}/r/UsedFor","CapableOf": f"{CONCEPTNET_BASE_URI}/r/CapableOf","AtLocation": f"{CONCEPTNET_BASE_URI}/r/AtLocation","Causes": f"{CONCEPTNET_BASE_URI}/r/Causes","HasSubevent": f"{CONCEPTNET_BASE_URI}/r/HasSubevent","HasFirstSubevent": f"{CONCEPTNET_BASE_URI}/r/HasFirstSubevent","HasLastSubevent": f"{CONCEPTNET_BASE_URI}/r/HasLastSubevent","HasPrerequisite": f"{CONCEPTNET_BASE_URI}/r/HasPrerequisite","HasProperty": f"{CONCEPTNET_BASE_URI}/r/HasProperty","MotivatedByGoal": f"{CONCEPTNET_BASE_URI}/r/MotivatedByGoal","ObstructedBy": f"{CONCEPTNET_BASE_URI}/r/ObstructedBy","Desires": f"{CONCEPTNET_BASE_URI}/r/Desires","CreatedBy": f"{CONCEPTNET_BASE_URI}/r/CreatedBy","Synonym": f"{CONCEPTNET_BASE_URI}/r/Synonym","Antonym": f"{CONCEPTNET_BASE_URI}/r/Antonym","DistinctFrom": f"{CONCEPTNET_BASE_URI}/r/DistinctFrom","DerivedFrom": f"{CONCEPTNET_BASE_URI}/r/DerivedFrom","SymbolOf": f"{CONCEPTNET_BASE_URI}/r/SymbolOf","DefinedAs": f"{CONCEPTNET_BASE_URI}/r/DefinedAs","MannerOf": f"{CONCEPTNET_BASE_URI}/r/MannerOf","LocatedNear": f"{CONCEPTNET_BASE_URI}/r/LocatedNear","HasContext": f"{CONCEPTNET_BASE_URI}/r/HasContext","SimilarTo": f"{CONCEPTNET_BASE_URI}/r/SimilarTo","EtymologicallyRelatedTo": f"{CONCEPTNET_BASE_URI}/r/EtymologicallyRelatedTo","EtymologicallyDerivedFrom": f"{CONCEPTNET_BASE_URI}/r/EtymologicallyDerivedFrom","CausesDesire": f"{CONCEPTNET_BASE_URI}/r/CausesDesire","MadeOf": f"{CONCEPTNET_BASE_URI}/r/MadeOf","ReceivesAction": f"{CONCEPTNET_BASE_URI}/r/ReceivesAction","ExternalURL": f"{CONCEPTNET_BASE_URI}/r/ExternalURL","NotDesires": f"{CONCEPTNET_BASE_URI}/r/NotDesires","NotUsedFor": f"{CONCEPTNET_BASE_URI}/r/NotUsedFor","NotCapableOf": f"{CONCEPTNET_BASE_URI}/r/NotCapableOf","NotHasProperty": f"{CONCEPTNET_BASE_URI}/r/NotHasProperty",}# Sorted list of (Label, Full_URL) tuples for Gradio dropdownsRELATION_CHOICES = sorted(CONCEPTNET_RELATIONS.items())# ============================================================================# 3. DATABASE SETUP & HELPERS# ============================================================================def log_progress(message, level="INFO"):"""Helper for logging with emoji prefixes."""timestamp = time.strftime("%H:%M:%S")prefix = {"INFO": "βΉοΈ ", "SUCCESS": "β ", "ERROR": "β", "WARN": "β οΈ ", "DEBUG": "π"}.get(level, "")print(f"[{timestamp}] {prefix} {message}")def check_remote_progress():"""Check HF Hub for the indexing progress file."""if not HF_TOKEN:log_progress("No HF_TOKEN. Assuming local DB or public repo.", "WARN")try:progress_path = hf_hub_download(repo_id=INDEXED_REPO_ID,filename=PROGRESS_FILENAME,repo_type="dataset")with open(progress_path, 'r') as f:return json.load(f)except Exception:return {"indexing_complete": False} # Fallbacktry:api = HfApi()api.repo_info(repo_id=INDEXED_REPO_ID, repo_type="dataset", token=HF_TOKEN)progress_path = hf_hub_download(repo_id=INDEXED_REPO_ID,filename=PROGRESS_FILENAME,repo_type="dataset",token=HF_TOKEN)with open(progress_path, 'r') as f:return json.load(f)except Exception as e:log_progress(f"Could not check remote progress: {e}", "WARN")return {"indexing_complete": False}def setup_database():"""Downloads the pre-indexed database from Hugging Face Hub.This should only be called once on app startup."""global DB_PATHlog_progress("Attempting to load indexed database...", "INFO")local_path = Path(INDEXED_DB_FILENAME)if local_path.exists() and local_path.stat().st_size > 1000000:log_progress(f"Found existing local DB: {local_path.resolve()}", "SUCCESS")DB_PATH = str(local_path.resolve())return DB_PATHprogress = check_remote_progress()if progress.get("indexing_complete"):try:log_progress(f"Downloading {INDEXED_DB_FILENAME} from {INDEXED_REPO_ID}...", "INFO")path = hf_hub_download(repo_id=INDEXED_REPO_ID,filename=INDEXED_DB_FILENAME,repo_type="dataset",token=HF_TOKEN)DB_PATH = pathlog_progress(f"Indexed DB loaded successfully from Hub: {path}", "SUCCESS")return pathexcept Exception as e:log_progress(f"Failed to download indexed DB: {e}", "ERROR")return Noneelse:log_progress("Remote indexing is not complete or progress file not found.", "ERROR")return Nonedef get_db_connection() -> sqlite3.Connection:"""Returns a new SQLite connection to the database.Includes performance PRAGMAs."""if DB_PATH is None:raise ConnectionError("Database path is not set. The lifespan startup event might have failed.")conn = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True, check_same_thread=False)conn.execute("PRAGMA journal_mode = OFF")conn.execute("PRAGMA synchronous = 0")conn.execute("PRAGMA cache_size = -256000") # 256MB cacheconn.execute("PRAGMA mmap_size = 4294967296") # 4GB mmapconn.execute("PRAGMA temp_store = MEMORY")return conn# ============================================================================# 4. API (FASTAPI) ENDPOINTS# ============================================================================# --- FIX 2: Define the lifespan event manager ---@asynccontextmanagerasync def lifespan(app: FastAPI):# --- Code to run ON STARTUP ---log_progress("Lifespan startup: Setting up database...", "INFO")try:if not setup_database():print("\n" + "="*70)print("β CRITICAL ERROR: Could not set up the database.")print(f" Please check connection or manually download '{INDEXED_DB_FILENAME}'")print(f" from '{INDEXED_REPO_ID}' and place it in this directory.")print("="*70 + "\n")else:print(f"β Database is ready at: {DB_PATH}")except Exception as e:print(f"β CRITICAL ERROR during database setup: {e}")traceback.print_exc()# --- App is now running ---yield# --- Code to run ON SHUTDOWN (optional) ---log_progress("Lifespan shutdown.", "INFO")# --- FIX 3: Pass the lifespan manager to the FastAPI app ---app = FastAPI(title="ConceptNet Explorer API",version="1.0",description="A versatile API for querying a ConceptNet SQLite database.",lifespan=lifespan # <-- Here)@app.get("/api", tags=["API"])def api_docs():"""API documentation - accessible at /api"""return {"name": "ConceptNet Explorer API","version": "1.0","endpoints": {"/api/profile/{word}": "Get a full semantic profile for a word.","/api/query": "Run a specific query for edges.","/api/relations": "List all available relation types.","/api/languages": "List all supported languages."},"examples": {"profile": "/api/profile/dog?lang=en&limit=10","query": f"/api/query?start_node=dog&relation_uri={CONCEPTNET_BASE_URI}/r/IsA&limit=20"},"note": "Visit the root path (/) for the Gradio UI."}@app.get("/api/profile/{word}", tags=["API"])def get_semantic_profile_json(word: str, lang: str = 'en', limit: int = 10):"""API Endpoint: Get a full semantic profile for a word as JSON."""if not word or lang not in TARGET_LANGUAGES:return JSONResponse(status_code=400,content={"error": "Invalid input. 'word' is required and 'lang' must be valid."})word_normalized = word.strip().lower().replace(' ', '_')like_path = f"{CONCEPTNET_BASE_URI}/c/{lang}/{word_normalized}%"result = {"query": {"word": word, "normalized": word_normalized, "lang": lang, "limit_per_relation": limit},"nodes_found": [],"relations": {},"total_edges_found": 0}try:1 unmodified linecursor = conn.cursor()cursor.execute("SELECT id, label FROM node WHERE id LIKE ? LIMIT 5", (like_path,))result["nodes_found"] = [{"id": nid, "label": label} for nid, label in cursor.fetchall()]if not result["nodes_found"]:return JSONResponse(status_code=404,content={"error": f"Word '{word}' (normalized: '{word_normalized}') not found in language '{lang}'."})for rel_name, rel_uri in RELATION_CHOICES:outgoing = []incoming = []4 unmodified linesWHERE e.start_id LIKE ? AND e.rel_id = ?ORDER BY e.weight DESCLIMIT ?""", (like_path, rel_uri, limit))outgoing = [{"target_label": label, "weight": weight, "target_id": eid}for label, weight, eid in cursor.fetchall()]cursor.execute("""3 unmodified linesWHERE e.end_id LIKE ? AND e.rel_id = ?ORDER BY e.weight DESCLIMIT ?""", (like_path, rel_uri, limit))incoming = [{"source_label": label, "weight": weight, "source_id": sid}for label, weight, sid in cursor.fetchall()]if outgoing or incoming:result["relations"][rel_name] = {"uri": rel_uri,"outgoing": outgoing,"incoming": incoming,"count": len(outgoing) + len(incoming)}result["total_edges_found"] += len(outgoing) + len(incoming)return JSONResponse(content=result)except Exception as e:log_progress(f"API /profile error: {e}", "ERROR")traceback.print_exc()return JSONResponse(status_code=500, content={"error": str(e)})@app.get("/api/query", tags=["API"])def query_edges_json(start_node: Optional[str] = None,relation_uri: Optional[str] = None,end_node: Optional[str] = None,lang: str = 'en',limit: int = 50):"""API Endpoint: Query edges with flexible filters."""query = """SELECTe.id as edge_id, s.id as start_id, r.id as relation_id, en.id as end_id,e.weight, s.label as start_label, r.label as relation_label, en.label as end_labelFROM edge eJOIN relation r ON e.rel_id = r.idJOIN node s ON e.start_id = s.idJOIN node en ON e.end_id = en.idWHERE 1=1"""params: List[Any] = []try:def build_node_pattern(node_str: str) -> str:if node_str.startswith(f'{CONCEPTNET_BASE_URI}/c/'):return f"{node_str}%"return f"{CONCEPTNET_BASE_URI}/c/{lang}/{node_str.strip().lower().replace(' ', '_')}%"with get_db_connection() as conn:if start_node:query += " AND s.id LIKE ?"params.append(build_node_pattern(start_node))if relation_uri:query += " AND r.id = ?"params.append(relation_uri)if end_node:query += " AND en.id LIKE ?"params.append(build_node_pattern(end_node))query += " ORDER BY e.weight DESC LIMIT ?"params.append(limit)df = pd.read_sql_query(query, conn, params=params)return {"query": {"start_node": start_node, "relation_uri": relation_uri, "end_node": end_node, "lang": lang, "limit": limit},"results": df.to_dict(orient='records'),"count": len(df)}except Exception as e:log_progress(f"API /query error: {e}", "ERROR")traceback.print_exc()return JSONResponse(status_code=500, content={"error": str(e)})@app.get("/api/relations", tags=["API"])def api_relations():"""API Endpoint: List all configured relations."""return JSONResponse(content={"relations": CONCEPTNET_RELATIONS})@app.get("/api/languages", tags=["API"])def api_languages():"""API Endpoint: List all configured languages."""return JSONResponse(content={"languages": TARGET_LANGUAGES})# ============================================================================# 5. GRADIO UI HELPER FUNCTIONS# ============================================================================def get_semantic_profile_ui(word: str, lang: str, progress=gr.Progress()):"""Gradio UI Function: Get semantic profile formatted as Markdown."""log_progress(f"UI Profile: {word} ({lang})", "INFO")if not word or lang not in TARGET_LANGUAGES:return "β οΈ Invalid input. Please provide a word and select a language."progress(0, desc="π Starting...")word_normalized = word.strip().lower().replace(' ', '_')like_path = f"{CONCEPTNET_BASE_URI}/c/{lang}/{word_normalized}%"output_md = f"# π§ Semantic Profile: '{word}' ({lang.upper()})\n\n"2 unmodified linescursor = conn.cursor()progress(0.05, desc="π Finding nodes...")cursor.execute("SELECT id, label FROM node WHERE id LIKE ? LIMIT 5", (like_path,))nodes = cursor.fetchall()if not nodes:return f"# π§ '{word}'\n\nβ οΈ **Word not found** (as `.../c/{lang}/{word_normalized}...`)"log_progress(f"Found {len(nodes)} nodes", "SUCCESS")output_md += "**Matching Nodes:**\n"for node_id, label in nodes[:3]:output_md += f"- **{label}** (ID: `{node_id}`)\n"output_md += "\n---\n"total_found = 0num_relations = len(RELATION_CHOICES)for i, (rel_name, rel_uri) in enumerate(RELATION_CHOICES):progress((i + 0.1) / num_relations, desc=f"π {rel_name}...")cursor.execute("""SELECT en.label, e.weightFROM edge e JOIN node en ON e.end_id = en.idWHERE e.start_id LIKE ? AND e.rel_id = ?ORDER BY e.weight DESC LIMIT 10""", (like_path, rel_uri))outgoing = cursor.fetchall()cursor.execute("""SELECT s.label, e.weightFROM edge e JOIN node s ON e.start_id = s.idWHERE e.end_id LIKE ? AND e.rel_id = ?ORDER BY e.weight DESC LIMIT 10""", (like_path, rel_uri))incoming = cursor.fetchall()if outgoing or incoming:output_md += f"### {rel_name} (`{rel_uri}`)\n\n"total_found += len(outgoing) + len(incoming)for label, weight in outgoing:output_md += f"- **{word}** β *{label}* `[{weight:.3f}]`\n"for label, weight in incoming:output_md += f"- *{label}* β **{word}** `[{weight:.3f}]`\n"output_md += "\n"progress((i + 1) / num_relations, desc=f"β {rel_name}")progress(1.0, desc="β Complete!")output_md += f"---\n**Total relations found:** {total_found}\n"log_progress(f"Complete: {total_found} relations", "SUCCESS")return output_mdexcept Exception as e:log_progress(f"UI Profile Error: {e}", "ERROR")traceback.print_exc()return f"**β An unexpected error occurred:**\n\n```\n{e}\n```"def run_query_ui(start_node: str, relation_uri: str, end_node: str, lang: str, limit: int, progress=gr.Progress()):"""Gradio UI Function: Query builder."""log_progress(f"UI Query: start={start_node}, rel={relation_uri}, end={end_node}, lang={lang}", "INFO")progress(0, desc="π Building query...")query = """SELECTs.label as start_label, r.label as relation_label, en.label as end_label,e.weight, s.id as start_id, r.id as relation_id, en.id as end_id, e.id as edge_idFROM edge eJOIN relation r ON e.rel_id = r.idJOIN node s ON e.start_id = s.idJOIN node en ON e.end_id = en.idWHERE 1=1"""params: List[Any] = []try:def build_node_pattern(node_str: str) -> str:if node_str.strip().startswith(f'{CONCEPTNET_BASE_URI}/c/'):return f"{node_str.strip()}%"return f"{CONCEPTNET_BASE_URI}/c/{lang}/{node_str.strip().lower().replace(' ', '_')}%"with get_db_connection() as conn:progress(0.3, desc="π Applying filters...")if start_node and start_node.strip():query += " AND s.id LIKE ?"params.append(build_node_pattern(start_node))if relation_uri and relation_uri.strip():query += " AND r.id = ?"params.append(relation_uri)if end_node and end_node.strip():query += " AND en.id LIKE ?"params.append(build_node_pattern(end_node))query += " ORDER BY e.weight DESC LIMIT ?"params.append(limit)progress(0.6, desc="β‘ Running query...")start_time = time.time()df = pd.read_sql_query(query, conn, params=params)1 unmodified lineprogress(1.0, desc="β Done!")log_progress(f"Query Done: {len(df)} rows in {elapsed:.2f}s", "SUCCESS")if df.empty:return pd.DataFrame(), f"β οΈ No results found ({elapsed:.2f}s)"cols_to_show = ['start_label', 'relation_label', 'end_label', 'weight','start_id', 'relation_id', 'end_id']df = df[cols_to_show]return df, f"β {len(df)} results in {elapsed:.2f}s"except Exception as e:log_progress(f"UI Query Error: {e}", "ERROR")traceback.print_exc()return pd.DataFrame(), f"β **Error:**\n\n```\n{e}\n```"def run_raw_query_ui(sql_query: str):"""Gradio UI Function: Raw SQL query."""if not sql_query.strip().upper().startswith("SELECT"):return pd.DataFrame(), "β **Error:** Only `SELECT` statements are allowed."try:with get_db_connection() as conn:start = time.time()1 unmodified lineelapsed = time.time() - startreturn df, f"β {len(df)} rows in {elapsed:.3f}s"except Exception as e:return pd.DataFrame(), f"β **Error:**\n\n```\n{e}\n```"def get_schema_info_ui():"""Gradio UI Function: Display schema information."""md = f"# π Database Schema\n\n"md += f"**Repo:** [{INDEXED_REPO_ID}](https://huggingface.co/datasets/{INDEXED_REPO_ID})\n"if DB_PATH:md += f"**Database File:** `{DB_PATH}`\n\n"else:md += "**Database File:** `NOT LOADED`\n\n"md += "β οΈ **Database not loaded.** Schema info may be incomplete. Check logs.\n"return mdtry:with get_db_connection() as conn:cursor = conn.cursor()md += "## Tables & Row Counts\n\n"cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")tables = [row[0] for row in cursor.fetchall()]for table in tables:cursor.execute(f"SELECT COUNT(*) FROM {table}")count = cursor.fetchone()[0]md += f"- **{table}:** {count:,} rows\n"md += "\n## Configured Relations\n\n"md += "This list populates the 'Query Builder' dropdown. The values are the full URLs used in the DB.\n\n"for name, uri in RELATION_CHOICES:md += f"- **{name}:** `{uri}`\n"except Exception as e:md += f"\n**β Error loading schema:**\n\n```\n{e}\n```\n"return md# ============================================================================# 6. GRADIO UI DEFINITION# ============================================================================def create_gradio_ui():"""Builds the consolidated Gradio interface."""with gr.Blocks(title="ConceptNet Explorer", theme=gr.themes.Soft(primary_hue="blue")) as demo:gr.Markdown("# π§ ConceptNet Explorer\n""An interface for querying the ConceptNet semantic network.")gr.Markdown(f"**Languages:** {', '.join([l.upper() for l in TARGET_LANGUAGES])} | "f"**Database:** `{INDEXED_REPO_ID}` | "f"**JSON API:** Access at `/api`")with gr.Tabs():with gr.TabItem("π Semantic Profile"):gr.Markdown("Explore all semantic relations for a single word. This queries all 34 relation types.")with gr.Row():profile_word_input = gr.Textbox(label="Word",placeholder="e.g., dog",value="dog",info="Enter a word")profile_lang_input = gr.Dropdown(choices=TARGET_LANGUAGES, value="en", label="Language")profile_btn = gr.Button("π Get Semantic Profile", variant="primary", size="lg")profile_output = gr.Markdown(label="Profile Results")gr.Examples(examples=[["dog", "en"], ["Hund", "de"], ["perro", "es"], ["chien", "fr"], ["gatto", "it"]],inputs=[profile_word_input, profile_lang_input])with gr.TabItem("β‘ Query Builder"):gr.Markdown("Construct a specific query using nodes and a relation.")with gr.Row():query_lang_input = gr.Dropdown(choices=TARGET_LANGUAGES, value="en", label="Node Language")query_limit_slider = gr.Slider(label="Result Limit", minimum=1, maximum=500, value=50, step=10)with gr.Row():query_start_input = gr.Textbox(label="Start Node",placeholder="e.g., dog (word) or /c/en/dog (URI)")query_rel_input = gr.Dropdown(label="Relation",choices=RELATION_CHOICES,value=f"{CONCEPTNET_BASE_URI}/r/IsA")query_end_input = gr.Textbox(label="End Node",placeholder="e.g., animal (word) or /c/en/animal (URI)")query_btn = gr.Button("βΆοΈ Run Query", variant="primary", size="lg")query_status_output = gr.Markdown()query_results_output = gr.DataFrame(label="Query Results",wrap=True,interactive=False)with gr.TabItem("π» Raw SQL"):gr.Markdown("**Warning:** Directly query the SQLite database. Only `SELECT` statements are allowed. ""Use the 'Schema' tab to see table names.")raw_sql_input = gr.Textbox(label="SQL Query",value=f"SELECT s.label, r.label, en.label, e.weight\nFROM edge e\nJOIN relation r ON e.rel_id = r.id\nJOIN node s ON e.start_id = s.id\nJOIN node en ON e.end_id = en.id\nWHERE s.id LIKE '{CONCEPTNET_BASE_URI}/c/en/dog%'\n AND r.id = '{CONCEPTNET_BASE_URI}/r/IsA'\nORDER BY e.weight DESC\nLIMIT 10",lines=5,max_lines=20)raw_btn = gr.Button("βΆοΈ Execute SQL")raw_status = gr.Markdown()raw_results = gr.DataFrame(label="SQL Results", interactive=False)with gr.TabItem("π Schema") as schema_tab:gr.Markdown("View the database schema and table counts.")schema_btn = gr.Button("π Load Schema Info")schema_output = gr.Markdown()with gr.TabItem("π API Docs"):gr.Markdown("## JSON API Endpoints\n""This Gradio app is mounted on a FastAPI server. You can use the following JSON API endpoints directly.")gr.JSON({"docs": "/api","profile": "/api/profile/{word}?lang=en&limit=10","query": f"/api/query?start_node=dog&relation_uri={CONCEPTNET_BASE_URI}/r/IsA&lang=en&limit=50","relations": "/api/relations","languages": "/api/languages"}, label="API Endpoints")gr.Markdown("### Example (cURL)\n""```bash\n# (Assumes app is running at localhost:7860)\ncurl http://localhost:7860/api/profile/dog?lang=en\n```\n"f"```bash\ncurl 'http://localhost:7860/api/query?start_node=dog&relation_uri={CONCEPTNET_BASE_URI}/r/IsA&limit=10'\n```")# --- Link UI components to functions ---profile_btn.click(fn=get_semantic_profile_ui,inputs=[profile_word_input, profile_lang_input],outputs=[profile_output],api_name="get_semantic_profile")query_btn.click(fn=run_query_ui,inputs=[query_start_input, query_rel_input, query_end_input, query_lang_input, query_limit_slider],outputs=[query_results_output, query_status_output],api_name="run_query")raw_btn.click(fn=run_raw_query_ui,inputs=[raw_sql_input],outputs=[raw_results, raw_status])schema_tab.select(fn=get_schema_info_ui,inputs=None,outputs=[schema_output])schema_btn.click(fn=get_schema_info_ui,inputs=None,outputs=[schema_output])return demo# ============================================================================# 7. APP MOUNTING & LAUNCH# ============================================================================# --- FIX 4: REMOVE the top-level call to setup_database() ---# This is now handled by the FastAPI lifespan eventlog_progress("Creating Gradio UI...", "INFO")demo = create_gradio_ui()log_progress("Mounting Gradio UI onto FastAPI app...", "INFO")app = gr.mount_gradio_app(app, demo, path="/")# ============================================================================# 8. MAIN EXECUTION BLOCK# ============================================================================# This block is for LOCAL execution (e.g., `python app.py`)# The Hugging Face platform will IGNORE this and run `app` using Gunicornif __name__ == "__main__":log_progress("="*60, "SUCCESS")log_progress("π (LOCAL) CONCEPTNET EXPLORER APP READY!", "SUCCESS")log_progress("="*60, "SUCCESS")log_progress("UI: http://localhost:7860/", "INFO")log_progress("API: http://localhost:7860/api", "INFO")log_progress(f" http://localhost:7860/api/profile/dog", "INFO")log_progress(f" http://localhost:7860/api/query?start_node=dog&relation_uri={CONCEPTNET_BASE_URI}/r/IsA", "INFO")log_progress("="*60, "SUCCESS")uvicorn.run("app:app", # Run the 'app' object from the 'app' filehost="0.0.0.0",port=7860,reload=True # Enable reload for local dev)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990911 unmodified line939495969798991001011021031044 unmodified lines1091101111121131141151161173 unmodified lines1211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541552 unmodified lines1581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543551 unmodified line3573583593603613623633643653663673683693703713723733743753763773783791 unmodified line381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541import gradio as grimport sqlite3import pandas as pdfrom huggingface_hub import hf_hub_download, HfApifrom fastapi import FastAPIfrom fastapi.responses import JSONResponseimport osimport timeimport jsonfrom typing import Optional# ===== CONFIGURATION =====TARGET_LANGUAGES = ['de', 'en', 'es', 'fr', 'it', 'ja', 'nl', 'pl', 'pt', 'ru', 'zh']INDEXED_REPO_ID = "cstr/conceptnet-de-indexed"INDEXED_DB_FILENAME = "conceptnet-de-indexed.db"PROGRESS_FILENAME = "indexing_progress.json"CONCEPTNET_BASE = "http://conceptnet.io"# =========================print(f"π Languages: {', '.join([l.upper() for l in TARGET_LANGUAGES])}")HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN") or os.environ.get("HF_API_TOKEN")def log_progress(message, level="INFO"):timestamp = time.strftime("%H:%M:%S")prefix = {"INFO": "βΉοΈ ", "SUCCESS": "β ", "ERROR": "β", "WARN": "β οΈ ", "DEBUG": "π"}.get(level, "")print(f"[{timestamp}] {prefix} {message}")def check_remote_progress():if not HF_TOKEN:return {"indexing_complete": False}try:api = HfApi()api.repo_info(repo_id=INDEXED_REPO_ID, repo_type="dataset", token=HF_TOKEN)progress_path = hf_hub_download(repo_id=INDEXED_REPO_ID, filename=PROGRESS_FILENAME, repo_type="dataset", token=HF_TOKEN)with open(progress_path, 'r') as f:return json.load(f)except:return {"indexing_complete": False}def create_indexed_database():progress = check_remote_progress()if progress.get("indexing_complete"):try:path = hf_hub_download(repo_id=INDEXED_REPO_ID, filename=INDEXED_DB_FILENAME, repo_type="dataset", token=HF_TOKEN)log_progress("Indexed DB loaded", "SUCCESS")return pathexcept:passreturn NoneDB_PATH = create_indexed_database()def get_db_connection():conn = sqlite3.connect(DB_PATH, check_same_thread=False)conn.execute("PRAGMA cache_size = -256000")conn.execute("PRAGMA mmap_size = 4294967296")return connRELATIONS = [("IsA", f"{CONCEPTNET_BASE}/r/IsA"),("PartOf", f"{CONCEPTNET_BASE}/r/PartOf"),("HasA", f"{CONCEPTNET_BASE}/r/HasA"),("UsedFor", f"{CONCEPTNET_BASE}/r/UsedFor"),("CapableOf", f"{CONCEPTNET_BASE}/r/CapableOf"),("Causes", f"{CONCEPTNET_BASE}/r/Causes"),("HasProperty", f"{CONCEPTNET_BASE}/r/HasProperty"),("Synonym", f"{CONCEPTNET_BASE}/r/Synonym"),("Antonym", f"{CONCEPTNET_BASE}/r/Antonym"),("AtLocation", f"{CONCEPTNET_BASE}/r/AtLocation"),("RelatedTo", f"{CONCEPTNET_BASE}/r/RelatedTo"),("DerivedFrom", f"{CONCEPTNET_BASE}/r/DerivedFrom"),]def get_semantic_profile_json(word: str, lang: str = 'en', max_per_relation: int = 10):"""Get semantic profile as JSON"""if not word or lang not in TARGET_LANGUAGES:return {"error": "Invalid input"}word = word.strip().lower().replace(' ', '_')like_path = f"{CONCEPTNET_BASE}/c/{lang}/{word}%"result = {"word": word,"language": lang,"nodes": [],"relations": {},"total_edges": 0}try:1 unmodified linecursor = conn.cursor()cursor.execute("SELECT id, label FROM node WHERE id LIKE ? LIMIT 5", (like_path,))result["nodes"] = [{"id": nid, "label": label} for nid, label in cursor.fetchall()]if not result["nodes"]:return {"error": "Word not found"}for rel_name, rel_url in RELATIONS:outgoing = []incoming = []4 unmodified linesWHERE e.start_id LIKE ? AND e.rel_id = ?ORDER BY e.weight DESCLIMIT ?""", (like_path, rel_url, max_per_relation))outgoing = [{"target": label, "weight": weight, "target_id": eid}for label, weight, eid in cursor.fetchall()]cursor.execute("""3 unmodified linesWHERE e.end_id LIKE ? AND e.rel_id = ?ORDER BY e.weight DESCLIMIT ?""", (like_path, rel_url, max_per_relation))incoming = [{"source": label, "weight": weight, "source_id": sid}for label, weight, sid in cursor.fetchall()]if outgoing or incoming:result["relations"][rel_name] = {"outgoing": outgoing,"incoming": incoming,"count": len(outgoing) + len(incoming)}result["total_edges"] += len(outgoing) + len(incoming)return resultexcept Exception as e:return {"error": str(e)}def get_semantic_profile(word, lang='en', progress=gr.Progress()):"""Get semantic profile with progress"""log_progress(f"Profile: {word} ({lang})", "INFO")if not word or lang not in TARGET_LANGUAGES:return "β οΈ Invalid input"progress(0, desc="π Starting...")word = word.strip().lower().replace(' ', '_')like_path = f"{CONCEPTNET_BASE}/c/{lang}/{word}%"output_md = f"# π§ Semantic Profile: '{word}' ({lang.upper()})\n\n"2 unmodified linescursor = conn.cursor()progress(0.05, desc="π Finding nodes...")cursor.execute("SELECT id, label FROM node WHERE id LIKE ? LIMIT 5", (like_path,))nodes = cursor.fetchall()if not nodes:return f"# π§ '{word}'\n\nβ οΈ Not found"log_progress(f"Found {len(nodes)} nodes", "SUCCESS")for node_id, label in nodes[:3]:output_md += f"**Node:** `{node_id}` β **{label}**\n"output_md += "\n"total = 0num_relations = len(RELATIONS)for i, (rel_name, rel_url) in enumerate(RELATIONS):progress((i + 0.1) / num_relations, desc=f"π {rel_name}...")output_md += f"## {rel_name}\n\n"found = Falsestart_time = time.time()cursor.execute("""SELECT en.label, e.weightFROM edge eJOIN node en ON e.end_id = en.idWHERE e.start_id LIKE ? AND e.rel_id = ?ORDER BY e.weight DESCLIMIT 10""", (like_path, rel_url))results = cursor.fetchall()elapsed = time.time() - start_timelog_progress(f" {rel_name} out: {len(results)} in {elapsed:.3f}s", "DEBUG")for label, weight in results:output_md += f"- **{word}** {rel_name} β *{label}* `[{weight:.3f}]`\n"found = Truetotal += 1cursor.execute("""SELECT s.label, e.weightFROM edge eJOIN node s ON e.start_id = s.idWHERE e.end_id LIKE ? AND e.rel_id = ?ORDER BY e.weight DESCLIMIT 10""", (like_path, rel_url))results = cursor.fetchall()for label, weight in results:output_md += f"- *{label}* {rel_name} β **{word}** `[{weight:.3f}]`\n"found = Truetotal += 1if not found:output_md += "*No results*\n"output_md += "\n"progress((i + 1) / num_relations, desc=f"β {rel_name}")progress(1.0, desc="β Complete!")output_md += f"---\n**Total relations:** {total}\n"log_progress(f"Complete: {total} relations", "SUCCESS")return output_mdexcept Exception as e:log_progress(f"Error: {e}", "ERROR")import tracebacktraceback.print_exc()return f"**β Error:** {e}"def query_edges_json(start_node: Optional[str] = None,relation: Optional[str] = None,end_node: Optional[str] = None,limit: int = 50):"""Query edges JSON"""query = """SELECTe.id, s.id, r.label, en.id, e.weight, s.label, en.labelFROM edge eJOIN relation r ON e.rel_id = r.idJOIN node s ON e.start_id = s.idJOIN node en ON e.end_id = en.idWHERE 1=1"""params = []try:with get_db_connection() as conn:if start_node:if start_node.startswith('http://'):pattern = f"{start_node}%"else:pattern = f"{CONCEPTNET_BASE}/c/en/{start_node}%"query += " AND s.id LIKE ?"params.append(pattern)if relation:if relation.startswith('http://'):rel_value = relationelif relation.startswith('/r/'):rel_value = f"{CONCEPTNET_BASE}{relation}"else:rel_value = f"{CONCEPTNET_BASE}/r/{relation}"query += " AND r.id = ?"params.append(rel_value)if end_node:if end_node.startswith('http://'):pattern = f"{end_node}%"else:pattern = f"{CONCEPTNET_BASE}/c/en/{end_node}%"query += " AND en.id LIKE ?"params.append(pattern)query += " ORDER BY e.weight DESC LIMIT ?"params.append(limit)df = pd.read_sql_query(query, conn, params=params)if df.empty:return {"results": [], "count": 0}df.columns = ['edge_id', 'start_id', 'relation', 'end_id', 'weight', 'start_label', 'end_label']return {"results": df.to_dict(orient='records'),"count": len(df)}except Exception as e:return {"error": str(e)}def run_query(start_node, relation, end_node, limit, progress=gr.Progress()):"""Query builder"""log_progress(f"Query: start={start_node}, rel={relation}, end={end_node}", "INFO")progress(0, desc="π Building...")query = """SELECTe.id, s.id, r.label, en.id, e.weight, s.label, en.labelFROM edge eJOIN relation r ON e.rel_id = r.idJOIN node s ON e.start_id = s.idJOIN node en ON e.end_id = en.idWHERE 1=1"""params = []try:with get_db_connection() as conn:progress(0.3, desc="π Filters...")if start_node and start_node.strip():if start_node.startswith('http://'):pattern = f"{start_node}%"else:pattern = f"{CONCEPTNET_BASE}/c/en/{start_node}%"query += " AND s.id LIKE ?"params.append(pattern)if relation and relation.strip():if relation.startswith('http://'):rel_value = relationelif relation.startswith('/r/'):rel_value = f"{CONCEPTNET_BASE}{relation}"else:rel_value = f"{CONCEPTNET_BASE}/r/{relation}"query += " AND r.id = ?"params.append(rel_value)if end_node and end_node.strip():if end_node.startswith('http://'):pattern = f"{end_node}%"else:pattern = f"{CONCEPTNET_BASE}/c/en/{end_node}%"query += " AND en.id LIKE ?"params.append(pattern)query += " ORDER BY e.weight DESC LIMIT ?"params.append(limit)progress(0.6, desc="β‘ Running...")start_time = time.time()df = pd.read_sql_query(query, conn, params=params)1 unmodified lineprogress(1.0, desc="β Done!")log_progress(f"Done: {len(df)} rows in {elapsed:.2f}s", "SUCCESS")if df.empty:return pd.DataFrame(), f"β οΈ No results ({elapsed:.2f}s)"df.columns = ['edge_id', 'start_id', 'relation', 'end_id', 'weight', 'start_label', 'end_label']return df, f"β {len(df)} results in {elapsed:.2f}s"except Exception as e:log_progress(f"Error: {e}", "ERROR")import tracebacktraceback.print_exc()return pd.DataFrame(), f"β {e}"def run_raw_query(sql_query):if not sql_query.strip().upper().startswith("SELECT"):return pd.DataFrame(), "β Only SELECT"try:with get_db_connection() as conn:start = time.time()1 unmodified lineelapsed = time.time() - startreturn df, f"β {len(df)} rows in {elapsed:.3f}s"except Exception as e:return pd.DataFrame(), f"β {e}"def get_schema_info():md = f"# π Schema\n\n"md += f"**Repo:** [{INDEXED_REPO_ID}](https://huggingface.co/datasets/{INDEXED_REPO_ID})\n\n"try:with get_db_connection() as conn:cursor = conn.cursor()md += "## Relations\n\n"cursor.execute("SELECT id, label FROM relation ORDER BY label LIMIT 20")for rel_id, label in cursor.fetchall():md += f"- **{label}:** `{rel_id}`\n"md += "\n## Tables\n\n"cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")for table, in cursor.fetchall():cursor.execute(f"SELECT COUNT(*) FROM {table}")md += f"- **{table}:** {cursor.fetchone()[0]:,} rows\n"except Exception as e:md += f"\nError: {e}\n"return md# ===== FASTAPI - Create app FIRST =====app = FastAPI(title="ConceptNet API", version="1.0")@app.get("/api")def api_docs():"""API documentation - accessible at /api"""return {"name": "ConceptNet API","version": "1.0","endpoints": {"/api/profile/{word}": "Semantic profile (params: lang, limit)","/api/query": "Query edges (params: start, relation, end, limit)","/api/relations": "List relations","/api/languages": "List languages"},"examples": {"profile": "/api/profile/dog?lang=en&limit=10","query": "/api/query?start=dog&relation=IsA&limit=20"},"note": "Visit root (/) for the Gradio UI"}@app.get("/api/profile/{word}")def api_profile(word: str, lang: str = "en", limit: int = 10):"""Get semantic profile"""return JSONResponse(get_semantic_profile_json(word, lang, limit))@app.get("/api/query")def api_query(start: Optional[str] = None,relation: Optional[str] = None,end: Optional[str] = None,limit: int = 50):"""Query edges"""return JSONResponse(query_edges_json(start, relation, end, limit))@app.get("/api/relations")def api_relations():"""List relations"""return JSONResponse({"relations": [{"name": name, "url": url} for name, url in RELATIONS]})@app.get("/api/languages")def api_languages():"""List languages"""return JSONResponse({"languages": TARGET_LANGUAGES})# ===== GRADIO UI =====with gr.Blocks(title="ConceptNet Explorer", theme=gr.themes.Soft()) as demo:gr.Markdown("# π§ ConceptNet Explorer")gr.Markdown(f"**Multi-language semantic network** | "f"**Languages:** {', '.join([l.upper() for l in TARGET_LANGUAGES])} | "f"**API:** `/api/profile/{{word}}` `/api/query`")with gr.Tabs():with gr.TabItem("π Semantic Profile"):gr.Markdown("**Explore semantic relations for any word**")with gr.Row():word_input = gr.Textbox(label="Word", placeholder="dog", value="dog")lang_input = gr.Dropdown(choices=TARGET_LANGUAGES, value="en", label="Language")semantic_btn = gr.Button("π Get Semantic Profile", variant="primary", size="lg")semantic_output = gr.Markdown()gr.Examples(examples=[["dog", "en"], ["hund", "de"], ["perro", "es"], ["chien", "fr"]],inputs=[word_input, lang_input])with gr.TabItem("β‘ Query Builder"):with gr.Row():start_input = gr.Textbox(label="Start", placeholder="dog")rel_input = gr.Textbox(label="Relation", placeholder="IsA", value="IsA")end_input = gr.Textbox(label="End", placeholder="")limit_slider = gr.Slider(label="Limit", minimum=1, maximum=200, value=50)query_btn = gr.Button("βΆοΈ Run Query", variant="primary", size="lg")status_output = gr.Markdown()results_output = gr.DataFrame(wrap=True)with gr.TabItem("π» Raw SQL"):raw_sql_input = gr.Textbox(label="SQL",value=f"SELECT e.*, r.label FROM edge e JOIN relation r ON e.rel_id = r.id WHERE e.start_id = '{CONCEPTNET_BASE}/c/en/dog' LIMIT 10",lines=3)raw_btn = gr.Button("βΆοΈ Execute")raw_status = gr.Markdown()raw_results = gr.DataFrame()with gr.TabItem("π Schema"):schema_btn = gr.Button("π Load Schema")schema_output = gr.Markdown()with gr.TabItem("π API"):gr.Markdown("## JSON API Endpoints\n")gr.Markdown("### API Documentation\n```\nGET /api\n```")gr.Markdown("### Get Semantic Profile\n```\nGET /api/profile/{word}?lang=en&limit=10\n```")gr.Markdown("### Query Edges\n```\nGET /api/query?start=dog&relation=IsA&limit=50\n```")gr.Markdown("### List Relations\n```\nGET /api/relations\n```")gr.Markdown("### Examples\n")gr.Markdown("```\ncurl https://your-space.hf.space/api/profile/dog?lang=en\n```")gr.Markdown("```\ncurl 'https://your-space.hf.space/api/query?start=dog&relation=IsA&limit=10'\n```")gr.Markdown("---\n""**Performance:** Exact match on rel_id for fast queries | ""**API:** Full REST API at `/api/*` endpoints")semantic_btn.click(get_semantic_profile, [word_input, lang_input], semantic_output)query_btn.click(run_query, [start_input, rel_input, end_input, limit_slider], [results_output, status_output])raw_btn.click(run_raw_query, raw_sql_input, [raw_results, raw_status])schema_btn.click(get_schema_info, None, schema_output)# ===== MOUNT GRADIO TO FASTAPI - Gradio at root, API at /api/* =====app = gr.mount_gradio_app(app, demo, path="/")if __name__ == "__main__":log_progress("="*60, "SUCCESS")log_progress("π APP READY!", "SUCCESS")log_progress("="*60, "SUCCESS")log_progress("UI: http://localhost:7860/", "INFO")log_progress("API: http://localhost:7860/api", "INFO")log_progress(" http://localhost:7860/api/profile/dog", "INFO")log_progress(" http://localhost:7860/api/query?start=dog&relation=IsA", "INFO")log_progress("="*60, "SUCCESS")import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)
app.py+337-557