Spaces:
Runtime error
Runtime error
Merge pull request #2 from Pushkar222-n/feature/OptimizePrompt
Browse filesFiles changed (9)
12345678910111213141516171819from pydantic_settings import BaseSettingsimport os
class Settings(BaseSettings): groq_api_key: str neo4j_uri: str neo4j_username: str neo4j_password: str neo4j_database: str aura_instanceid: str aura_instancename: str model_name: str
class Config: env_file = '.env'
settings = Settings() # type: ignore3 unmodified lines45678968 unmodified lines787980818283848586878889906 unmodified lines9798991001011021033 unmodified linesimport uvicornfrom src.api.schemas import RecommendationRequest, RecommendationResponseimport timefrom src.retrieval.rag_pipeline import AnimeRAGPipeline68 unmodified linesrecommendations=result["recommendations"],retrieved_count=result["retrieved_count"],metadata={"model": "llama-3.3-70b-versatile","retriever_k": rag_pipeline.retriever_k,"Time taken for LLM + vector search": str(end_time - start_time)})except Exception as e:raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail=f"Error processing request: {str(e)}")6 unmodified linesreturn {"total_anime": rag_pipeline.retriever.collection.count(),"embedding_model": "all-MiniLM-L6-v2","llm_model": "llama-3.1-70b-versatile","retrieval_k": rag_pipeline.retriever_k}3 unmodified lines456789101168 unmodified lines80818283848586878889909192936 unmodified lines1001011021031041051063 unmodified linesimport uvicornfrom src.api.schemas import RecommendationRequest, RecommendationResponseimport timefrom config import settingsimport tracebackfrom src.retrieval.rag_pipeline import AnimeRAGPipeline68 unmodified linesrecommendations=result["recommendations"],retrieved_count=result["retrieved_count"],metadata={"model": settings.model_name,"retriever_k": rag_pipeline.retriever_k,"Time taken for LLM + vector search": str(end_time - start_time)})except Exception as e:traceback.print_exc()raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail=f"Error processing request: {str(e)}")6 unmodified linesreturn {"total_anime": rag_pipeline.retriever.collection.count(),"embedding_model": "all-MiniLM-L6-v2","llm_model": settings.model_name,"retrieval_k": rag_pipeline.retriever_k}
123456789101112131415161718192021222324from neo4j import GraphDatabaseimport pandas as pdfrom src.utils.neo4j_client import Neo4j_Client
class AnimeGraphLoader: """Loads anime into Neo4j Graph"""
def __init__(self): self.client = Neo4j_Client()
def clear_database(self): """Delete all nodes (use carefully !)""" query = "MATCH (n) DETACH DELETE n" self.client.run_query(query) def create_constraints(self): """Create uniqueness constraints for performance""" queries = [ "CREATE CONSTRAINT anime_id IF NOT EXISTS FOR (a: Anime) REQUIRE a.mal_id IS UNIQUE", "CREATE CONSTRAINT genre_name IF NOT EXISTS FOR (g:Genre) REQUIRE g.name IS UNIQUE", "CREATE CONSTRAINT theme_name IF NOT EXISTS FOR (t:Theme) REQUIRE t.name IS UNIQUE", "CREATE CONSTRAINT demographic_name IF NOT EXISTS FOR (d:Demographic) REQUIRE d.name IS UNIQUE", "CREAE CONSTRAINT content_type IF NOT EXISTS FOR (t: Type) REQUIRE t.type IS UNIUE" ]1 unmodified line23456789101112131415162 unmodified lines192021222324251 unmodified linefrom groq import Groqfrom dotenv import load_dotenvimport loggingload_dotenv()logger = logging.getLogger(__name__)class GroqLLM:"""Wrapper for Groq API"""def __init__(self, model: str = "llama-3.3-70b-versatile"):"""Initialize Groq Client2 unmodified lines- llama-3.1-8b-instant: Faster, good enough for most tasks"""self.client = Groq()self.model = modellogger.info(f"Initialized Groq with model {self.model}")1 unmodified line23456789101112131415162 unmodified lines192021222324251 unmodified linefrom groq import Groqfrom dotenv import load_dotenvimport loggingfrom config import settingslogger = logging.getLogger(__name__)class GroqLLM:"""Wrapper for Groq API"""def __init__(self, model: str = "llama-3.1-8b-instant"):"""Initialize Groq Client2 unmodified lines- llama-3.1-8b-instant: Faster, good enough for most tasks"""self.client = Groq(api_key=settings.groq_api_key)self.model = modellogger.info(f"Initialized Groq with model {self.model}")
27 unmodified lines282930313233343536373839404142436 unmodified lines5051525354555 unmodified lines6162636465666727 unmodified linescontext = "\n".join(context_parts)prompt = f"""You are an expert anime recommendation assistant. A user has asked for recommendations, and I've retrieved some potentially relevant anime from the database.First: If the user is asking for a comparison or opinion on specific anime,provide thoughtful comparison rather than a list of recommendations.If recommendations, onlt then:Your task is to:1. Analyze the user's request carefully, paying attention to specific preferences (tone, themes, etc.)2. Evaluate each retrieved anime against their user's criteria3. Select the {n_recommendations} BEST matches that truly fit what they're asking for4. Explain why each recommendation fits their requestUser's Query:"{user_query}"6 unmodified lines- Don't just list all retrieved anime - SELECT the best {n_recommendations} that truly match- For each recommendation, explain in 1-2 sentences WHY it matches their request- If some retrieved anime DON'T match the user's specific criteria, exclude them- Be honest if none of the retrieved anime are great matchesFormat your response as:5 unmodified lines[Continue for {n_recommendations} recommendations]If you think the retrieved anime don't match the request well, say so and explain what type of anime would be better."""return prompt27 unmodified lines282930313233343536373839404142436 unmodified lines50515253545556575 unmodified lines6364656667686970717273747527 unmodified linescontext = "\n".join(context_parts)prompt = f"""You are an expert anime recommendation assistant. A user has asked for recommendations, and you are provided in context relevant similar anime from the database.First: If the user is asking for a comparison or opinion on specific anime,provide thoughtful comparison rather than a list of recommendations.## 1. If recommendations, only then:Your task is to:1. Analyze the user's request carefully, paying attention to specific preferences (tone, themes, etc.)2. Evaluate each retrieved anime against their user's criteria3. Select the {n_recommendations} BEST matches that truly fit what they're asking for4. Explain why each recommendation fits their request. Answer in a way, that sounds really casual, super relaxed, and don't explain your "system thinking" such as "User has asked for ...., So here they are..." or any such variations.User's Query:"{user_query}"6 unmodified lines- Don't just list all retrieved anime - SELECT the best {n_recommendations} that truly match- For each recommendation, explain in 1-2 sentences WHY it matches their request- If some retrieved anime DON'T match the user's specific criteria, exclude them- If some retrieved anime are the sequel (can be identified by name or other information) do not mention them, UNLESS user specifically asks.-> If user SPEICIFICALLY Ask about some sequel, and there's no synopsis, tell the User something similar to Synopsis of prequel(that might be in context) and additionally answer based on other featurs like genre, demographics, etc. DO NOT INVENT SYNOPSIS !!!- Be honest if none of the retrieved anime are great matchesFormat your response as:5 unmodified lines[Continue for {n_recommendations} recommendations]If you think the retrieved anime don't match the request well, say so and explain what type of anime would be better.## 2. If the user wants to talk casually about some anime they recently watched, engage into meaningful conversation with them, and ONLY when it seems user wants recommendations, give recommendation like mentioned in ##1 above.## 3. FOR ANY OTHER Gibberish queries, not matching to the "Anime world" except some occasional GREETINGS(in which case you have to greet properly), just give a generic message that "You are not capable of answering that, politely".**Response Style**: Friendly, Casual, and do not mention the programmer(or anything similar to what/how you process/look for data). Just a Intelligent Bot answering to a user."""return prompt
1 unmodified line23456716 unmodified lines242526272829301 unmodified linefrom src.llm.groq_client import GroqLLMfrom src.llm.prompts import create_recommendation_prompt, create_system_promptimport logginglogger = logging.getLogger(__name__)16 unmodified linesrecommendation_n: How many to recommend in final output"""self.retriever = retriever or AnimeRetriever()self.llm = llm or GroqLLM(model="llama-3.3-70b-versatile")self.retriever_k = retriever_kself.recommendation_n = recommendation_n1 unmodified line234567816 unmodified lines252627282930311 unmodified linefrom src.llm.groq_client import GroqLLMfrom src.llm.prompts import create_recommendation_prompt, create_system_promptimport loggingfrom config import settingslogger = logging.getLogger(__name__)16 unmodified linesrecommendation_n: How many to recommend in final output"""self.retriever = retriever or AnimeRetriever()self.llm = llm or GroqLLM(model=settings.model_name)self.retriever_k = retriever_kself.recommendation_n = recommendation_n
51 unmodified lines525354555657585960616263646540 unmodified lines10610710810951 unmodified linesdistance = results["distances"][0][i] # type: ignore# Genre filtering (if specified)if genre_filter:if genre_filter.lower() not in metadata["genres"].lower(): # type: ignorecontinueanime_info = {"mal_id": results["ids"][0][i],"title": metadata["title"],"genres": metadata["genres"],"score": metadata["score"],"type": metadata["type"],"year": metadata["year"],40 unmodified linesprint("\n=== Test 4: Scored by Filter ===")results = retriever.search("adventure", n_results=5, min_score=8.0)for anime in results:print(f"- {anime['title']} (score: {anime['score']}) (scored_by: {anime['scored_by']})")51 unmodified lines52535455565758596061626364656640 unmodified lines10710810911011151 unmodified linesdistance = results["distances"][0][i] # type: ignore# Genre filtering (if specified)if genre_filter and "genres" in metadata:# type: ignoreif genre_filter.lower() not in metadata["genres"].lower():continueanime_info = {"mal_id": results["ids"][0][i],"title": metadata["title"],"genres": metadata.get("genres", ""),"score": metadata["score"],"type": metadata["type"],"year": metadata["year"],40 unmodified linesprint("\n=== Test 4: Scored by Filter ===")results = retriever.search("adventure", n_results=5, min_score=8.0)for anime in results:print(f"- {anime['title']} (score: {anime['score']}) (scored_by: {anime['scored_by']})")
1234567891011121314151617import osfrom dotenv import load_dotenvfrom neo4j import GraphDatabaseload_dotenv()class Neo4j_Client:"""Neo4j database client"""def __init__(self):uri = os.getenv("NEO4J_URI")user = os.getenv("NEO4J_USERNAME")password = os.getenv("NEO4J_PASSWORD")try:self.driver = GraphDatabase.driver(uri, auth=(user, password)) # type: ignore12345678910111213141516from dotenv import load_dotenvfrom neo4j import GraphDatabasefrom config import settingsclass Neo4j_Client:"""Neo4j database client"""def __init__(self):uri = settings.neo4j_uriuser = settings.neo4j_usernamepassword = settings.neo4j_passwordtry:self.driver = GraphDatabase.driver(uri, auth=(user, password)) # type: ignore
1231 unmodified line56789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import gradio as grimport requestsimport os1 unmodified lineAPI_URL = os.getenv("API_URL", "http://127.0.0.1:8000")def get_recommendations(query, min_score, genre_filter):"""Call the fastapi backend"""try:payload = {"query": query,"n_results": 5}if min_score > 0:payload["min_score"] = min_scoreif genre_filter and genre_filter != None:payload["genre_filter"] = genre_filterresponse = requests.post(f"{API_URL}/recommend",json=payload,timeout=30)response.raise_for_status()result = response.json()print(result["metadata"])return result["recommendations"]except requests.exceptions.RequestException as e:return f"Error connecting to the API. Make sure FastAPI server is running. \nDetails: {str(e)}"except Exception as e:return f"Error: {str(e)}"with gr.Blocks(title="Anime Recommender") as demo:gr.Markdown("""# Anime Recommendation SystemPowered by RAG(Retrieval-Augmented Generation)Ask for anime recommendations and get AI-powered suggestions!""")with gr.Row():with gr.Column(scale=2):query_input = gr.Textbox(label="What are you looking for?",placeholder="e.g., 'Anime similar to Death Note but lighter' or 'Romantic comedy set in high school'",lines=3)with gr.Row():min_score_slider = gr.Slider(minimum=0,maximum=10,value=0,step=0.5,label="Minimum Rating this animes should have (0 = no filter)")genre_dropdown = gr.Dropdown(choices=["None", "Action", "Comedy", "Drama","Romance", "Sci-Fi", "Fantasy", "Thriller"],value="None",label="Genre Filter (optional)")submit_btn = gr.Button("Get Recommendations",variant="primary", size="lg")with gr.Column(scale=3):output = gr.Markdown(label="Recommendations")# Examplesgr.Examples(examples=[["Anime similar to Death Note but lighter", 0, "None"],["Romantic comedy set in high school", 7.5, "Comedy"],["Dark psychological thriller", 8.0, "None"],["Action anime with epic fights", 7.0, "Action"],],inputs=[query_input, min_score_slider, genre_dropdown],)# Connect button to functionsubmit_btn.click(fn=get_recommendations,inputs=[query_input, min_score_slider, genre_dropdown],outputs=output)# Launchif __name__ == "__main__":print("Starting Gradio UI...")print("Make sure FastAPI server is running at http://localhost:8000")demo.launch(server_name="0.0.0.0",server_port=7860,share=True # Set to True to get public URL)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171 unmodified line119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523# import gradio as gr# import requests# import os# API_URL = os.getenv("API_URL", "http://127.0.0.1:8000")# def get_recommendations(query, min_score, genre_filter, n_results):# """Call the fastapi backend"""# try:# payload = {# "query": query,# "n_results": n_results# }# if min_score > 0:# payload["min_score"] = min_score# if genre_filter and genre_filter != None:# payload["genre_filter"] = genre_filter# response = requests.post(# f"{API_URL}/recommend",# json=payload,# timeout=30# )# response.raise_for_status()# result = response.json()# print(result["metadata"])# return result["recommendations"]# except requests.exceptions.RequestException as e:# return f"Error connecting to the API. Make sure FastAPI server is running. \nDetails: {str(e)}"# except Exception as e:# return f"Error: {str(e)}"# with gr.Blocks(title="Anime Recommender") as demo:# gr.Markdown("""# # Anime Recommendation System# Powered by RAG(Retrieval-Augmented Generation)# Ask for anime recommendations and get AI-powered suggestions!# """)# with gr.Row():# with gr.Column(scale=2):# query_input = gr.Textbox(# label="What are you looking for?",# placeholder="e.g., 'Anime similar to Death Note but lighter' or 'Romantic comedy set in high school'",# lines=3# )# with gr.Row():# min_score_slider = gr.Slider(# minimum=0,# maximum=10,# value=0,# step=0.5,# label="Minimum Rating this animes should have (0 = no filter)"# )# genre_dropdown = gr.Dropdown(# choices=["None", "Action", "Comedy", "Drama",# "Romance", "Sci-Fi", "Fantasy", "Thriller"],# value="None",# label="Genre Filter (optional)"# )# n_results_dropdown = gr.Slider(# minimum=1,# maximum=8,# value=3,# step=1,# label="Number of recommendation you want to get"# )# submit_btn = gr.Button("Get Recommendations",# variant="primary", size="lg")# with gr.Column(scale=3):# output = gr.Markdown(label="Recommendations")# # Examples# gr.Examples(# examples=[# ["Anime similar to Death Note but lighter", 0, "None", 3],# ["Romantic comedy set in high school", 7.5, "Comedy", 4],# ["Dark psychological thriller", 8.0, "None", 2],# ["Action anime with epic fights", 7.0, "Action", 1],# ],# inputs=[query_input, min_score_slider,# genre_dropdown, n_results_dropdown],# )# # Connect button to function# submit_btn.click(# fn=get_recommendations,# inputs=[query_input, min_score_slider,# genre_dropdown, n_results_dropdown],# outputs=output# )# # Launch# if __name__ == "__main__":# print("Starting Gradio UI...")# print("Make sure FastAPI server is running at http://localhost:8000")# demo.launch(# server_name="0.0.0.0",# server_port=7860,# share=True # Set to True to get public URL# )import gradio as grimport requestsimport os1 unmodified lineAPI_URL = os.getenv("API_URL", "http://127.0.0.1:8000")def get_recommendations(query, min_score, genre_filter, n_results):try:payload = {"query": query, "n_results": int(n_results)}if min_score > 0:payload["min_score"] = min_scoreif genre_filter and genre_filter != "None":payload["genre_filter"] = genre_filterresponse = requests.post(f"{API_URL}/recommend", json=payload, timeout=30)response.raise_for_status()result = response.json()print(result["metadata"])return result["recommendations"]except requests.exceptions.RequestException as e:return f"**Connection Error** — Make sure FastAPI is running.\n\n`{str(e)}`"except Exception as e:return f"**Error:** {str(e)}"css = """@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600&family=DM+Serif+Display:ital@0;1&display=swap');:root {--bg: #1c1714;--surface: #241e1a;--card: #2d2520;--border: #3d3028;--accent: #d4845a;--gold: #c9a97a;--text: #f5ede3;--sub: #d0bfae;--muted: #9a8878;--faint: #6a5a4a;--radius: 16px;--shadow: 0 4px 28px rgba(0,0,0,0.4);}/* ── GLOBAL ── */body, .gradio-container {background: var(--bg) !important;font-family: 'DM Sans', sans-serif !important;color: var(--text) !important;}footer { display: none !important; }.gradio-container {max-width: 980px !important;margin: 0 auto !important;padding: 0 36px !important;}/* ── HEADER ── */.app-header { text-align: center; padding: 56px 0 40px; }.app-header h1 {font-family: 'DM Serif Display', serif !important;font-size: 46px !important;font-weight: 400 !important;color: var(--text) !important;margin: 0 0 8px !important;letter-spacing: -0.5px;}.app-header h1 em { font-style: italic; color: var(--accent); }.app-header p { font-size: 15px; color: var(--sub); margin: 0; }.header-line { width: 44px; height: 2px; background: var(--accent); border-radius: 2px; margin: 16px auto 0; opacity: 0.75; }/* ── STEP CARDS ── */.step-card {background: var(--card);border-radius: var(--radius);padding: 28px 32px 26px;margin-bottom: 14px;box-shadow: var(--shadow);border: 1px solid var(--border);}.step-label {font-size: 11px; font-weight: 600; letter-spacing: 0.18em;text-transform: uppercase; color: var(--muted);margin-bottom: 16px; display: flex; align-items: center; gap: 10px;}.step-label .num {width: 21px; height: 21px; background: var(--accent); color: #1c1714;border-radius: 50%; display: inline-flex; align-items: center;justify-content: center; font-size: 10px; font-weight: 700;}/* ── INPUTS ── */textarea, input[type="text"] {background: var(--surface) !important;border: 1.5px solid var(--border) !important;border-radius: 10px !important;color: var(--text) !important;font-family: 'DM Sans', sans-serif !important;font-size: 15px !important;transition: border-color 0.2s, box-shadow 0.2s !important;}textarea::placeholder, input::placeholder { color: var(--faint) !important; }textarea:focus, input:focus {border-color: var(--accent) !important;box-shadow: 0 0 0 3px rgba(212,132,90,0.15) !important;outline: none !important;}label > span {font-size: 13px !important; font-weight: 500 !important;color: var(--sub) !important; letter-spacing: 0 !important;text-transform: none !important;}/* ── SLIDER ── */input[type="range"] { accent-color: var(--accent) !important; }/* ── SUBMIT BUTTON ── */#submit-btn button {width: 100% !important;background: var(--accent) !important;color: #1c1714 !important;border: none !important;border-radius: 12px !important;font-family: 'DM Sans', sans-serif !important;font-size: 15px !important;font-weight: 700 !important;padding: 17px !important;cursor: pointer !important;letter-spacing: 0.03em !important;transition: background 0.2s, transform 0.15s, box-shadow 0.2s !important;box-shadow: 0 4px 20px rgba(212,132,90,0.30) !important;}#submit-btn button:hover {background: var(--gold) !important;transform: translateY(-2px) !important;box-shadow: 0 8px 28px rgba(212,132,90,0.42) !important;}#submit-btn button:active { transform: translateY(0) !important; }/* ── LOADER ── */#ao-loader { display: none; text-align: center; padding: 44px 0 36px; }.ao-loader-phrase {font-family: 'DM Serif Display', serif;font-size: 20px; font-style: italic;color: var(--text); margin-bottom: 24px;min-height: 30px; transition: opacity 0.35s;}.ao-dots { display: flex; justify-content: center; gap: 10px; }.ao-dots span {width: 9px; height: 9px; background: var(--accent);border-radius: 50%; animation: aobounce 1.2s infinite ease-in-out;}.ao-dots span:nth-child(2) { animation-delay: 0.18s; background: var(--gold); }.ao-dots span:nth-child(3) { animation-delay: 0.36s; background: var(--faint); }@keyframes aobounce {0%, 80%, 100% { transform: translateY(0) scale(0.75); opacity: 0.35; }40% { transform: translateY(-11px) scale(1.15); opacity: 1; }}/* ── OUTPUT BOX ── *//* Target the Gradio Markdown block container via elem_id */#ao-output-wrap,#ao-output-wrap > .wrap,div#ao-output-wrap {background: var(--card) !important;border-radius: var(--radius) !important;border: 1px solid var(--border) !important;box-shadow: var(--shadow) !important;padding: 32px 36px !important;margin-top: 4px !important;transition: opacity 0.45s !important;}/* The actual prose inside Markdown */#ao-output-wrap .prose,#ao-output-wrap .md,#ao-output-wrap > div {color: var(--sub) !important;}#ao-output-wrap p,#ao-output-wrap .prose p {font-size: 14.5px !important;line-height: 1.78 !important;color: var(--sub) !important;margin: 0 0 10px !important;}#ao-output-wrap h1, #ao-output-wrap h2,#ao-output-wrap .prose h1, #ao-output-wrap .prose h2 {font-family: 'DM Serif Display', serif !important;font-size: 22px !important;font-weight: 400 !important;color: var(--text) !important;padding-bottom: 10px !important;border-bottom: 1px solid var(--border) !important;margin: 28px 0 12px !important;}#ao-output-wrap h2:first-child,#ao-output-wrap .prose h2:first-child { margin-top: 0 !important; }#ao-output-wrap h3,#ao-output-wrap .prose h3 {font-size: 15px !important;color: var(--accent) !important;font-weight: 600 !important;margin: 0 0 5px !important;}#ao-output-wrap strong,#ao-output-wrap .prose strong { color: var(--text) !important; font-weight: 600 !important; }#ao-output-wrap em,#ao-output-wrap .prose em { color: var(--gold) !important; }#ao-output-wrap code,#ao-output-wrap .prose code {background: var(--surface) !important;color: var(--accent) !important;padding: 2px 7px !important;border-radius: 5px !important;font-size: 13px !important;border: 1px solid var(--border) !important;}#ao-output-wrap ul,#ao-output-wrap .prose ul { padding-left: 18px !important; }#ao-output-wrap li,#ao-output-wrap .prose li {font-size: 14.5px !important;line-height: 1.72 !important;color: var(--sub) !important;margin-bottom: 4px !important;}/* ── EXAMPLES ── */.examples-label {font-size: 11px; font-weight: 600; letter-spacing: 0.18em;text-transform: uppercase; color: var(--faint); margin: 26px 0 12px;}.gr-samples-table td, .examples-holder td {background: var(--card) !important;border: 1px solid var(--border) !important;border-radius: 8px !important;color: var(--sub) !important;font-size: 13px !important; padding: 10px 15px !important;transition: all 0.15s !important; cursor: pointer !important;font-family: 'DM Sans', sans-serif !important;}.gr-samples-table tr:hover td, .examples-holder tr:hover td {background: var(--accent) !important;color: #1c1714 !important;border-color: var(--accent) !important;}.gr-samples-header, .gr-samples-header th { display: none !important; }label[data-testid="block-label"] { display: none !important; }.examples-holder > label { display: none !important; }/* ── SCROLLBAR ── */::-webkit-scrollbar { width: 5px; }::-webkit-scrollbar-track { background: var(--bg); }::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }::-webkit-scrollbar-thumb:hover { background: var(--faint); }"""with gr.Blocks(title="Anime Oracle",css=css,theme=gr.themes.Base(primary_hue="orange",neutral_hue="slate",font=gr.themes.GoogleFont("DM Sans"),).set(body_background_fill="#1c1714",body_text_color="#f5ede3",block_background_fill="#2d2520",block_border_color="#3d3028",input_background_fill="#241e1a",input_border_color="#3d3028",button_primary_background_fill="#d4845a",button_primary_text_color="#1c1714",)) as demo:gr.HTML("""<div class="app-header"><h1>Find your next <em>obsession.</em></h1><p>Describe your mood — we'll find the perfect anime.</p><div class="header-line"></div></div>""")# Step 1gr.HTML('<div class="step-card"><div class="step-label"><span class="num">1</span> What are you in the mood for?</div>')query_input = gr.Textbox(label="", show_label=False, lines=3,placeholder='"Something like Attack on Titan but more emotional" or "Cozy slice-of-life with great friendships"')gr.HTML("</div>")# Step 2gr.HTML('<div class="step-card"><div class="step-label"><span class="num">2</span> Any preferences? <span style="font-weight:300;color:#6a5a4a;margin-left:4px;font-size:10px;">optional</span></div>')with gr.Row():genre_dropdown = gr.Dropdown(choices=["None", "Action", "Comedy", "Drama","Romance", "Sci-Fi", "Fantasy", "Thriller"],value="None", label="Genre", scale=1)min_score_slider = gr.Slider(minimum=0, maximum=10, value=0, step=0.5, label="Minimum rating (0 = any)", scale=2)gr.HTML("</div>")# Step 3gr.HTML('<div class="step-card"><div class="step-label"><span class="num">3</span> How many results?</div>')n_results_slider = gr.Slider(minimum=1, maximum=8, value=3, step=1, label="", show_label=False)gr.HTML("</div>")submit_btn = gr.Button("Find my anime →", variant="primary", elem_id="submit-btn")# Loading buffergr.HTML("""<div id="ao-loader"><div class="ao-loader-phrase">Scanning the anime universe…</div><div class="ao-dots"><span></span><span></span><span></span></div></div>""")# Output — elem_id so CSS can target it reliablyoutput = gr.Markdown(value="*Your recommendations will appear here ✦*",elem_id="ao-output-wrap")# Examplesgr.HTML('<div class="examples-label">Try an example</div>')gr.Examples(examples=[["Something like Death Note but with a lighter tone", 0, "None", 3],["Romantic comedy with lovable characters", 7.5, "Comedy", 4],["Dark psychological thriller with twists", 8.0, "Thriller", 2],["Epic action with incredible fights", 7.0, "Action", 5],["Wholesome feel-good slice of life", 6.0, "Drama", 3],],inputs=[query_input, min_score_slider,genre_dropdown, n_results_slider],label="")# Loader JSgr.HTML("""<script>(function() {const PHRASES = ["Scanning the anime universe\u2026","Consulting the oracle\u2026","Traversing story arcs\u2026","Matching your vibe\u2026","Sifting through thousands of titles\u2026","Almost there\u2026"];let phraseTimer = null, phraseIdx = 0;function startLoader() {const loader = document.getElementById('ao-loader');const wrap = document.getElementById('ao-output-wrap');if (loader) loader.style.display = 'block';if (wrap) wrap.style.opacity = '0.15';phraseIdx = 0;const el = document.querySelector('.ao-loader-phrase');if (el) el.textContent = PHRASES[0];clearInterval(phraseTimer);phraseTimer = setInterval(() => {phraseIdx = (phraseIdx + 1) % PHRASES.length;if (el) {el.style.opacity = '0';setTimeout(() => { el.textContent = PHRASES[phraseIdx]; el.style.opacity = '1'; }, 300);}}, 1800);}function stopLoader() {clearInterval(phraseTimer);const loader = document.getElementById('ao-loader');const wrap = document.getElementById('ao-output-wrap');if (loader) loader.style.display = 'none';if (wrap) { wrap.style.transition = 'opacity 0.5s ease'; wrap.style.opacity = '1'; }}document.addEventListener('click', function(e) {if (e.target && e.target.closest('#submit-btn')) {startLoader();setTimeout(stopLoader, 25000);}});function watchOutput() {const target = document.getElementById('ao-output-wrap');if (!target) { setTimeout(watchOutput, 500); return; }new MutationObserver(stopLoader).observe(target, { childList: true, subtree: true, characterData: true });}watchOutput();})();</script>""")submit_btn.click(fn=get_recommendations, inputs=[query_input, min_score_slider, genre_dropdown, n_results_slider], outputs=output)query_input.submit(fn=get_recommendations, inputs=[query_input, min_score_slider, genre_dropdown, n_results_slider], outputs=output)if __name__ == "__main__":print("Starting Anime Oracle...")demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
config.pyAdded+19
src/api/main.py+5-2
src/data_ingestion/load_to_neo4j.pyAdded+24
src/llm/groq_client.py+3-3
src/llm/prompts.py+12-4
src/retrieval/rag_pipeline.py+2-1
src/retrieval/vector_search.py+6-4
src/utils/neo4j_client.py+4-5
ui/gradio_app.py+491-70