File size: 8,543 Bytes
2c19561
 
 
80e413a
387dd80
 
 
 
 
 
 
 
 
 
 
 
 
2c19561
4430fb4
387dd80
4430fb4
698a444
387dd80
698a444
387dd80
f26fac2
387dd80
 
 
 
698a444
387dd80
 
 
 
 
f26fac2
387dd80
 
 
 
 
 
 
 
 
 
 
 
 
 
c15e02b
387dd80
c15e02b
387dd80
 
 
 
 
 
 
 
 
 
 
c15e02b
387dd80
c15e02b
387dd80
f26fac2
 
387dd80
f26fac2
 
387dd80
 
 
 
c15e02b
4430fb4
 
387dd80
4430fb4
698a444
387dd80
 
 
f26fac2
387dd80
f26fac2
387dd80
 
 
 
 
 
f26fac2
387dd80
c0b3c17
387dd80
 
 
 
 
f26fac2
387dd80
f26fac2
387dd80
 
 
 
f26fac2
387dd80
f26fac2
387dd80
f26fac2
387dd80
f26fac2
387dd80
f26fac2
387dd80
c15e02b
f26fac2
 
 
 
 
dffab2b
 
387dd80
2c19561
4430fb4
c15e02b
4430fb4
dffab2b
c15e02b
f26fac2
 
 
 
c15e02b
387dd80
 
 
 
 
 
 
 
 
 
f26fac2
387dd80
 
 
 
f26fac2
 
387dd80
f26fac2
387dd80
 
 
 
 
f26fac2
387dd80
 
 
 
 
 
c15e02b
698a444
f26fac2
 
 
 
c15e02b
f26fac2
 
 
 
387dd80
 
 
c15e02b
 
f26fac2
c15e02b
 
f26fac2
c15e02b
 
 
f26fac2
 
 
 
c15e02b
 
f26fac2
387dd80
f26fac2
c15e02b
f26fac2
c15e02b
 
f26fac2
 
 
c15e02b
f26fac2
 
c15e02b
387dd80
f26fac2
387dd80
 
 
c15e02b
387dd80
c15e02b
387dd80
 
 
 
dffab2b
c15e02b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import gradio as gr
import pandas as pd
import numpy as np
import os
import random
from sklearn.metrics.pairwise import cosine_similarity

# --- SAFE IMPORT BLOCK ---
# Prevents crash if advanced ML libraries are missing
try:
    import joblib
    from sentence_transformers import SentenceTransformer
    from huggingface_hub import hf_hub_download
    LIBRARIES_AVAILABLE = True
except ImportError:
    LIBRARIES_AVAILABLE = False
    print("⚠️ Warning: Advanced ML libraries missing. Running in Simulation Mode.")

# ==========================================
# 1. LOAD MODELS & DATA (FAIL-SAFE)
# ==========================================

print("πŸ”„ System Startup...")

# Global Variables
MODE = "SIMULATION" 
PREDICTION_MODEL = None
EMBEDDINGS = None
EMBEDDING_MODEL = None
DATASET = None

# 1.1 Attempt to load real AI models
if LIBRARIES_AVAILABLE:
    try:
        print("⏳ Attempting to load AI Models...")
        
        # Load Embedder
        EMBEDDING_MODEL = SentenceTransformer('all-MiniLM-L6-v2')
        
        # Check and load local files
        if os.path.exists("play_embeddings.npy") and os.path.exists("playticker_engine.pkl"):
            EMBEDDINGS = np.load("play_embeddings.npy")
            PREDICTION_MODEL = joblib.load("playticker_engine.pkl")
            MODE = "PRODUCTION (AI-POWERED)"
            print("βœ… SUCCESS: Real AI Models Loaded.")
        else:
            print("⚠️ Files not found on disk. Switching to Logic Fallback.")
            
    except Exception as e:
        print(f"❌ Error loading models: {e}")
        print("⚠️ Switching to Logic Fallback.")

# 1.2 Attempt to load dataset (CSV)
try:
    if LIBRARIES_AVAILABLE:
        # Attempt to download from Repo
        dataset_path = hf_hub_download(
            repo_id="meirnm13/playticker-nba-momentum",
            filename="synthetic_nba_momentum_data.csv",
            repo_type="dataset"
        )
        DATASET = pd.read_csv(dataset_path)
        print(f"βœ… Loaded Dataset: {len(DATASET)} rows.")
    else:
        raise Exception("No libraries")
except Exception as e:
    print(f"⚠️ Could not load CSV ({e}). Generating dummy data.")
    DATASET = pd.DataFrame({
        'play_description': [
            "LeBron James throws down a monster dunk", 
            "Stephen Curry hits a deep three pointer", 
            "Timeout called by the Miami Heat", 
            "Turnover by James Harden",
            "Giannis blocks the shot"
        ] * 20,
        'player_name': ["LeBron James", "Stephen Curry", "Team", "James Harden", "Giannis Antetokounmpo"] * 20,
        'team': ["Lakers", "Warriors", "Heat", "Clippers", "Bucks"] * 20,
        'momentum_score': [0.85, 0.92, -0.1, -0.6, 0.75] * 20
    })

# ==========================================
# 2. LOGIC ENGINES (HYBRID)
# ==========================================

def heuristic_logic(text):
    text = str(text).lower()
    score = 0.0
    if any(x in text for x in ["dunk", "3-pointer", "win", "clutch", "lead", "steal", "block"]): 
        score = random.uniform(0.6, 0.95)
    elif any(x in text for x in ["miss", "turnover", "foul", "lose", "brick", "timeout"]): 
        score = random.uniform(-0.7, -0.3)
    else: 
        score = random.uniform(-0.2, 0.2)
    return score

def predict_momentum(user_input_text):
    if not user_input_text: return "", 0.0
    momentum_score = 0.0
    
    if MODE.startswith("PRODUCTION") and PREDICTION_MODEL is not None:
        try:
            embedding = EMBEDDING_MODEL.encode([user_input_text])
            momentum_score = PREDICTION_MODEL.predict(embedding.reshape(1, -1))[0]
            if isinstance(momentum_score, (str, int, np.integer)):
                 mapping = {0: -0.8, 1: 0.0, 2: 0.8}
                 momentum_score = mapping.get(momentum_score, 0.5)
        except:
            momentum_score = heuristic_logic(user_input_text)
    else:
        momentum_score = heuristic_logic(user_input_text)

    # Visualization
    if momentum_score > 0.4:
        category, color, icon = "HIGH POSITIVE", "#10b981", "πŸ”₯"
    elif momentum_score > 0.1:
        category, color, icon = "POSITIVE", "#22c55e", "βœ…"
    elif momentum_score < -0.4:
        category, color, icon = "HIGH NEGATIVE", "#ef4444", "πŸ›‘"
    else:
        category, color, icon = "NEUTRAL", "#6b7280", "βš–οΈ"

    html_output = f"""
    <div style="text-align:center; padding:20px; border:3px solid {color}; 
                background:{color}10; border-radius:15px;">
        <h1 style="color:{color}; margin:0;">{icon} {category}</h1>
        <div style="font-size:40px; color:{color}; font-weight:bold;">{float(momentum_score):.3f}</div>
        <div style="font-size:12px; color:#888;">System Mode: {MODE}</div>
    </div>
    """
    return html_output, float(momentum_score)

# ==========================================
# 3. RECOMMENDATION PIPELINE
# ==========================================

def find_similar_plays(user_input_text, top_k=5):
    # Fixed: Always return a DataFrame, even if empty
    if not user_input_text:
        return pd.DataFrame(columns=['Similarity', 'Play', 'Player', 'Score'])

    results = []
    if MODE.startswith("PRODUCTION") and EMBEDDINGS is not None:
        try:
            input_embedding = EMBEDDING_MODEL.encode([user_input_text])
            similarities = cosine_similarity(input_embedding, EMBEDDINGS)[0]
            top_indices = similarities.argsort()[-top_k:][::-1]
            
            for idx in top_indices:
                play = DATASET.iloc[idx]
                results.append({
                    'Similarity': f"{similarities[idx]:.2f}",
                    'Play': str(play['play_description'])[:80] + "...",
                    'Player': play['player_name'],
                    'Score': f"{play['momentum_score']:.2f}"
                })
            return pd.DataFrame(results)
        except:
            pass
    
    # Fallback
    try:
        sample = DATASET.sample(top_k)
        for _, play in sample.iterrows():
            results.append({
                'Similarity': "N/A (Sim)",
                'Play': str(play['play_description'])[:80] + "...",
                'Player': play['player_name'],
                'Score': f"{play['momentum_score']:.2f}"
            })
    except:
        pass
        
    return pd.DataFrame(results)

# ==========================================
# 4. MAIN ANALYZER (UI HANDLER)
# ==========================================

def analyze_play(user_input):
    # FIXED: Return valid empty states instead of None to prevent Gradio Crash
    if not user_input or len(str(user_input).strip()) < 2:
        return "", 0, pd.DataFrame(columns=['Similarity', 'Play', 'Player', 'Score'])
    
    html, score = predict_momentum(user_input)
    sim_df = find_similar_plays(user_input)
    return html, score, sim_df

# ==========================================
# 5. GRADIO INTERFACE
# ==========================================

custom_css = ".gradio-container {max-width: 1100px !important; margin: auto;}"

with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="orange")) as demo:
    
    gr.HTML(f"""<div style="text-align:center;">
        <h1 style="color:#f59e0b;">πŸ€ PlayTicker Pro</h1>
        <p style="color:#888;">System Status: {MODE}</p>
    </div>""")
    
    with gr.Row():
        with gr.Column():
            input_text = gr.Textbox(label="Play Description", placeholder="E.g., LeBron hits a clutch three...", lines=3)
            btn = gr.Button("Analyze", variant="primary")
            
            # FIXED: Added cache_examples=False to prevent startup timeout
            gr.Examples(
                examples=[
                    ["LeBron James hits a clutch three-pointer"],
                    ["Steph Curry turnover leading to a fast break"],
                    ["Giannis blocks the shot"]
                ],
                inputs=input_text,
                cache_examples=False 
            )
            
        with gr.Column():
            out_html = gr.HTML(label="Prediction")
            out_score = gr.Number(visible=False)
            
    gr.Markdown("### πŸ” Similar Historical Plays")
    out_table = gr.Dataframe(headers=['Similarity', 'Play', 'Player', 'Score'])
    
    with gr.Accordion("πŸ“š Dataset Explorer", open=False):
        gr.Dataframe(DATASET.head(50) if DATASET is not None else [], interactive=False)

    btn.click(analyze_play, input_text, [out_html, out_score, out_table])

if __name__ == "__main__":
    demo.launch()