# Making a minor change to force gradio deploy to re-prompt import gradio as gr import textwrap import pandas as pd import numpy as np import os, shutil from sentence_transformers import SentenceTransformer import faiss from whoosh.index import create_in from whoosh.fields import Schema, TEXT, ID, NUMERIC from whoosh.qparser import QueryParser # --- Setup: Data Loading, Model Initialization, Index Building --- DATA_PATH = "/content/nhtsa_combined_llm.csv" # Changed path for HF Space, assuming data is uploaded or copied here # Check if data exists, if not, create dummy data for demonstration on HF Spaces without actual data upload if not os.path.exists(DATA_PATH): print("Creating dummy data for demonstration on Hugging Face Spaces.") df = pd.DataFrame({ 'id': [1, 2, 3], 'make': ['Toyota', 'Honda', 'Tesla'], 'model': ['Camry', 'Accord', 'Model S'], 'year': [2017, 2018, 2020], 'component': ['ENGINE', 'BRAKES', 'BATTERY'], 'subject': ['Stalling', 'Failure', 'Fire'], 'summary': ['Engine stalling problems.', 'Brake failure complaints.', 'Battery fire incidents.'], 'source': ['complaint', 'complaint', 'recall'] }) df['text_for_index'] = df['make'] + ' ' + df['model'] + ' ' + df['component'] + ' ' + df['subject'] + ' ' + df['summary'] df.to_csv(DATA_PATH, index=False) else: print(f"Loading data from {DATA_PATH}") df = pd.read_csv(DATA_PATH) # Basic data cleaning/preprocessing as in original notebook df = df.dropna(subset=["summary"]) df["year"] = pd.to_numeric(df["year"], errors="coerce").fillna(0).astype(int) for col in ["make", "model", "component", "subject", "summary", "source"]: df[col] = df[col].fillna("").astype(str) df["text_for_index"] = ( df["make"] + " " + df["model"] + " " + df["component"] + " " + df["subject"] + " " + df["summary"] ) print("Creating sentence embeddings...") model = SentenceTransformer("all-MiniLM-L6-v2") embeddings = model.encode(df["text_for_index"].tolist(), show_progress_bar=False) embeddings = np.array(embeddings).astype("float32") print("Building FAISS index...") dimension = embeddings.shape[1] index = faiss.IndexFlatL2(dimension) index.add(embeddings) print("Building Whoosh keyword index...") schema = Schema( id=ID(stored=True), make=TEXT(stored=True), model=TEXT(stored=True), year=NUMERIC(stored=True), component=TEXT(stored=True), subject=TEXT(stored=True), summary=TEXT(stored=True), source=TEXT(stored=True), text_for_index=TEXT(stored=True) ) WHOOSH_INDEX_DIR = "./whoosh_index" if not os.path.exists(WHOOSH_INDEX_DIR): os.mkdir(WHOOSH_INDEX_DIR) ix = create_in(WHOOSH_INDEX_DIR, schema) writer = ix.writer() for _, row in df.iterrows(): writer.add_document( id=str(row["id"]), make=row["make"], model=row["model"], year=int(row["year"]), component=row["component"], subject=row["subject"], summary=row["summary"], source=row["source"], text_for_index=row["text_for_index"] ) writer.commit() # --- Hybrid Search Function --- def hybrid_search(query, top_k=10, weight_semantic=0.6): # Keyword Search with ix.searcher() as searcher: parser = QueryParser("text_for_index", ix.schema) parsed_query = parser.parse(query) results = searcher.search(parsed_query, limit=top_k) keyword_hits = {hit["id"]: hit.score for hit in results} # Semantic Search query_emb = model.encode([query]).astype("float32") D, I = index.search(query_emb, top_k) semantic_hits = {str(df.iloc[i]["id"]): float(1.0 / (1.0 + D[0][rank])) for rank, i in enumerate(I[0])} # Combine Scores combined_scores = {} for id_, score in semantic_hits.items(): combined_scores[id_] = weight_semantic * score for id_, score in keyword_hits.items(): combined_scores[id_] = combined_scores.get(id_, 0) + (1 - weight_semantic) * score # Sort and Format Results sorted_hits = sorted(combined_scores.items(), key=lambda x: x[1], reverse=True)[:top_k] results = [] for doc_id, score in sorted_hits: row = df[df["id"].astype(str) == doc_id].iloc[0] results.append({ "id": doc_id, "make": row["make"], "model": row["model"], "year": int(row["year"]), "component": row["component"], "subject": row["subject"], "summary": row["summary"][:200] + "...", "source": row["source"], "score": round(score, 4) }) return results # --- LLM Summarization Function --- from transformers import pipeline model_name_llm = "mistralai/Mistral-7B-Instruct-v0.2" # Initialize summarizer only once print(f"Loading LLM: {model_name_llm}...") summarizer = pipeline( "text-generation", model=model_name_llm, device_map="auto", torch_dtype="auto" ) print("LLM loaded successfully.") def summarize_vehicle_issues(make, model, year, top_k=10): query = f"common issues for {year} {make} {model}" retrieved_docs = hybrid_search(query, top_k=top_k) context = "" for doc in retrieved_docs: context += ( f"[{doc['make']} {doc['model']} {doc['year']}] " f"{doc['summary']}\n(Source: {doc['source']})\n\n" ) prompt = f""" You are an automotive safety analyst. Based ONLY on the official NHTSA recall and complaint records below, summarize the most common issues for the {year} {make} {model}. Identify main problem categories, components involved, and possible recall IDs. Keep the summary factual, concise, and cite example sources. Records: {context} Summary: """ response = summarizer( prompt, max_new_tokens=300, do_sample=False, temperature=0.3 )[0]["generated_text"] return response, retrieved_docs # --- Gradio UI Functions --- def clean_summary(raw_text: str) -> str: if "Summary:" in raw_text: raw_text = raw_text.split("Summary:", 1)[1].strip() return raw_text.strip() def ui_summarize(make, model, year, top_k): try: year = int(year) except ValueError: return "Please enter a valid year (e.g., 2017).", "" answer, docs = summarize_vehicle_issues(make, model, year, top_k=top_k) answer_clean = clean_summary(answer) answer_wrapped = textwrap.fill(answer_clean, width=110) sources_lines = [] for d in docs: line = ( f"- **{d['make']} {d['model']} {d['year']}** " f"({d['component']}) – {d['summary'][:160]}..." f" _(Source: {d['source']})_" ) sources_lines.append(line) sources_text = "\n".join(sources_lines) if sources_lines else "No matching records found." return answer_wrapped, sources_text # --- Gradio Interface Definition --- with gr.Blocks() as demo: gr.Markdown("# 🚗 NHTSA Vehicle Issue Explorer") gr.Markdown( "Enter a vehicle make, model, and year. The app will search NHTSA data " "and summarize the most common issues using your hybrid search + LLM." ) with gr.Row(): make_input = gr.Textbox(label="Make", value="Toyota", placeholder="e.g., Toyota") model_input = gr.Textbox(label="Model", value="Camry", placeholder="e.g., Camry") year_input = gr.Textbox(label="Year", value="2017", placeholder="e.g., 2017") topk_input = gr.Slider( minimum=3, maximum=20, value=7, step=1, label="Number of records to retrieve (top_k)" ) run_button = gr.Button("🔍 Analyze Vehicle Issues") summary_output = gr.Textbox( label="LLM Summary of Common Issues", lines=12 ) sources_output = gr.Markdown( label="Retrieved NHTSA Records" ) run_button.click( fn=ui_summarize, inputs=[make_input, model_input, year_input, topk_input], outputs=[summary_output, sources_output] ) demo.launch()