reddmann007 commited on
Commit
8936721
Β·
verified Β·
1 Parent(s): abeee3a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -0
app.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from smolagents import CodeAgent, HfEngine, tool
4
+ from qdrant_client import QdrantClient
5
+ from qdrant_client.models import PointStruct, VectorParams, Distance, Filter, FieldCondition, MatchValue
6
+ from sentence_transformers import SentenceTransformer
7
+
8
+ # --- 1. Setup ---
9
+ client = QdrantClient(url=os.getenv("QDRANT_URL"), api_key=os.getenv("QDRANT_API_KEY"))
10
+ embed_model = SentenceTransformer("all-MiniLM-L6-v2")
11
+ collection_name = "cricket_analysis"
12
+
13
+ # Starter Match Config
14
+ STARTER_URL = "https://www.espncricinfo.com/series/icc-men-s-t20-world-cup-2024-1411166/south-africa-vs-india-final-1415755/ball-by-ball-commentary"
15
+ STARTER_ID = "T20_WC_Final_2024"
16
+
17
+ if not client.collection_exists(collection_name):
18
+ client.create_collection(
19
+ collection_name=collection_name,
20
+ vectors_config=VectorParams(size=384, distance=Distance.COSINE)
21
+ )
22
+
23
+ # --- 2. Professional Search Tool ---
24
+ @tool
25
+ def search_cricket_database(query: str, active_match_id: str) -> str:
26
+ """
27
+ Search the ball-by-ball database for match events.
28
+ Args:
29
+ query: The user's question.
30
+ active_match_id: The ID of the match to filter results by.
31
+ """
32
+ query_vector = embed_model.encode(query).tolist()
33
+
34
+ results = client.search(
35
+ collection_name=collection_name,
36
+ query_vector=query_vector,
37
+ query_filter=Filter(
38
+ must=[FieldCondition(key="match_id", match=MatchValue(value=active_match_id))]
39
+ ),
40
+ limit=8
41
+ )
42
+
43
+ if not results:
44
+ return "No specific match events found in the database for this query."
45
+
46
+ return "\n\n".join([f"[Over {r.payload.get('over_number')}] {r.payload['text']}" for r in results])
47
+
48
+ # --- 3. Professional Agent ---
49
+ # The prompt ensures a high-level analytical tone
50
+ system_prompt = """
51
+ You are a Lead Cricket Strategy Analyst. Your tone is professional, technical, and data-driven.
52
+ When answering questions about the match:
53
+ 1. Use the 'search_cricket_database' tool to retrieve facts.
54
+ 2. Focus on key turning points, strike rates, and bowling variations mentioned in the commentary.
55
+ 3. If the data is missing, state: 'The provided commentary does not contain specific details on this event.'
56
+ """
57
+
58
+ agent = CodeAgent(
59
+ tools=[search_cricket_database],
60
+ model=HfEngine("meta-llama/Llama-3-70B-Instruct"),
61
+ system_prompt=system_prompt
62
+ )
63
+
64
+ # --- 4. Logic & UI ---
65
+ def chat_fn(message, history, active_match_id):
66
+ prompt = f"Using context from match {active_match_id}: {message}"
67
+ response = agent.run(prompt)
68
+ history.append((message, response))
69
+ return "", history
70
+
71
+ def ingest_ui_handler(url, match_id):
72
+ # This would call your ingestion function (web scraping + upserting)
73
+ return f"Processing match {match_id} from {url}...", match_id
74
+
75
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
76
+ gr.Markdown("# 🏏 Elite Cricket Analytics Portal")
77
+
78
+ with gr.Row():
79
+ active_id = gr.Textbox(label="Active Match Focus", value=STARTER_ID, interactive=False)
80
+
81
+ with gr.Accordion("Ingest New Match Data", open=False):
82
+ url_input = gr.Textbox(label="Cricinfo URL")
83
+ new_id_input = gr.Textbox(label="New Match ID")
84
+ load_btn = gr.Button("Initialize Analysis")
85
+ status = gr.Markdown()
86
+
87
+ chatbot = gr.Chatbot(label="Analysis Feed")
88
+ msg = gr.Textbox(label="Query the Analyst")
89
+
90
+ msg.submit(chat_fn, [msg, chatbot, active_id], [msg, chatbot])
91
+ load_btn.click(ingest_ui_handler, [url_input, new_id_input], [status, active_id])
92
+
93
+ # Starter Match Loader
94
+ def check_starter():
95
+ count = client.count(collection_name=collection_name).count
96
+ if count == 0:
97
+ print("Pre-loading Starter Match...")
98
+ # Here you would trigger the initial scraping for STARTER_URL
99
+
100
+ demo.load(check_starter)
101
+
102
+ demo.launch()