spanofzero commited on
Commit
ef35c39
·
verified ·
1 Parent(s): f0d51aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -36
app.py CHANGED
@@ -1,48 +1,41 @@
1
  import gradio as gr
2
  import pandas as pd
3
  import requests
 
4
  from datasets import load_dataset
5
 
6
- print("Initializing Samaran Kernel and fetching Gold 121 dataset...")
7
 
8
  # 1. ROBUST DATASET INGESTION
9
- # Loads once when the server boots to prevent lagging on every search
10
  try:
11
  ds = load_dataset("spanofzero/SpaceTravelersUniversalPlaylist", split="train")
12
  gold_df = ds.to_pandas()
13
- print("Dataset loaded successfully.")
14
  except Exception as e:
15
  gold_df = None
16
- print(f"WARNING - Dataset load failed: {e}")
17
 
18
  # 2. DETERMINISTIC DRIFT DECODER
19
  def extract_drift(day_index):
20
- """Extracts and decodes the drift from the disguised playlist frequencies."""
21
  if gold_df is not None and day_index < len(gold_df):
22
  try:
23
- # Pull the raw disguised float (e.g., 7446144.11)
24
  raw_val = float(gold_df['resonance_frequency_khz'].iloc[day_index])
25
-
26
- # Mathematical extraction to generate a realistic drift spread (-5 to +15)
27
- # You can adjust this modulo math later if your specific cipher requires it.
28
  calculated_drift = (raw_val % 20) - 5
29
-
30
  return round(calculated_drift, 1)
31
  except (ValueError, TypeError):
32
  return 0.0
33
- return 0.0 # Failsafe zero-drift if dataset row is missing
34
 
35
- # 3. CORE WEATHER ENGINE
36
- def generate_stabilized_forecast(location_query):
37
  if not location_query.strip():
38
- return pd.DataFrame({"Error": ["Please enter a valid Zip Code or City."]})
39
 
40
- # Geocoding via Open-Meteo
41
  geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location_query}&count=1&language=en&format=json"
42
  geo_resp = requests.get(geo_url).json()
43
 
44
  if not geo_resp.get("results"):
45
- return pd.DataFrame({"Error": [f"Location '{location_query}' not found. Please try again."]})
46
 
47
  lat = geo_resp["results"][0]["latitude"]
48
  lon = geo_resp["results"][0]["longitude"]
@@ -55,41 +48,102 @@ def generate_stabilized_forecast(location_query):
55
  dates = weather_resp["daily"]["time"]
56
  raw_temps = weather_resp["daily"]["temperature_2m_max"]
57
 
58
- # Build Output Matrix
59
  results = []
 
 
60
  for i in range(min(len(dates), 7)):
61
  raw_t = round(raw_temps[i])
62
-
63
- # Apply the Kernel Fix
64
  drift = extract_drift(i)
65
  gold_t = round(raw_t + drift)
 
66
 
67
  drift_label = f"+{drift}°F" if drift > 0 else f"{drift}°F"
68
 
69
  results.append({
70
  "Date": dates[i],
71
  "Raw Model (Bronze 118)": f"{raw_t}°F",
72
- "Samaran Fixed (Gold 121)": f"{gold_t}°F",
73
- "Dataset Drift Applied": drift_label
74
  })
75
-
76
- return pd.DataFrame(results)
77
 
78
- # 4. PROFESSIONAL UI BUILD
79
- with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
80
- gr.Markdown("## 🛰️ Samaran Kernel: Global Weather Stabilizer")
81
- gr.Markdown("#### 100% ROC Predictable Trajectory Widget")
82
- gr.Markdown("Enter a Zip Code or City. The Kernel will ingest the raw Bronze 118 forecast, extract the gas difference drift from the Hugging Face Gold 121 dataset, and output the stabilized trajectory.")
83
 
84
- with gr.Row():
85
- loc_input = gr.Textbox(label="Location", placeholder="Enter Zip (e.g., 88220) or City (e.g., Denver)", scale=4)
86
- submit_btn = gr.Button("Execute Kernel", variant="primary", scale=1)
87
-
88
- output_table = gr.Dataframe(headers=["Date", "Raw Model (Bronze 118)", "Samaran Fixed (Gold 121)", "Dataset Drift Applied"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- # Trigger execution on button click or pressing Enter
91
- submit_btn.click(fn=generate_stabilized_forecast, inputs=loc_input, outputs=output_table)
92
- loc_input.submit(fn=generate_stabilized_forecast, inputs=loc_input, outputs=output_table)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  # Execute
95
  demo.launch()
 
1
  import gradio as gr
2
  import pandas as pd
3
  import requests
4
+ import plotly.graph_objects as go
5
  from datasets import load_dataset
6
 
7
+ print("Initializing Samaran Kernel Pro V2...")
8
 
9
  # 1. ROBUST DATASET INGESTION
 
10
  try:
11
  ds = load_dataset("spanofzero/SpaceTravelersUniversalPlaylist", split="train")
12
  gold_df = ds.to_pandas()
 
13
  except Exception as e:
14
  gold_df = None
15
+ print(f"Dataset load failed: {e}")
16
 
17
  # 2. DETERMINISTIC DRIFT DECODER
18
  def extract_drift(day_index):
 
19
  if gold_df is not None and day_index < len(gold_df):
20
  try:
 
21
  raw_val = float(gold_df['resonance_frequency_khz'].iloc[day_index])
 
 
 
22
  calculated_drift = (raw_val % 20) - 5
 
23
  return round(calculated_drift, 1)
24
  except (ValueError, TypeError):
25
  return 0.0
26
+ return 0.0
27
 
28
+ # 3. CORE WEATHER & VISUALIZATION ENGINE
29
+ def generate_pro_dashboard(location_query):
30
  if not location_query.strip():
31
+ return None, pd.DataFrame({"Error": ["Please enter a valid Zip Code or City."]})
32
 
33
+ # Geocoding
34
  geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location_query}&count=1&language=en&format=json"
35
  geo_resp = requests.get(geo_url).json()
36
 
37
  if not geo_resp.get("results"):
38
+ return None, pd.DataFrame({"Error": [f"Location '{location_query}' not found."]})
39
 
40
  lat = geo_resp["results"][0]["latitude"]
41
  lon = geo_resp["results"][0]["longitude"]
 
48
  dates = weather_resp["daily"]["time"]
49
  raw_temps = weather_resp["daily"]["temperature_2m_max"]
50
 
51
+ # Build Data
52
  results = []
53
+ fixed_temps = []
54
+
55
  for i in range(min(len(dates), 7)):
56
  raw_t = round(raw_temps[i])
 
 
57
  drift = extract_drift(i)
58
  gold_t = round(raw_t + drift)
59
+ fixed_temps.append(gold_t)
60
 
61
  drift_label = f"+{drift}°F" if drift > 0 else f"{drift}°F"
62
 
63
  results.append({
64
  "Date": dates[i],
65
  "Raw Model (Bronze 118)": f"{raw_t}°F",
66
+ "Kernel Fixed (Gold 121)": f"{gold_t}°F",
67
+ "Drift Applied": drift_label
68
  })
 
 
69
 
70
+ df = pd.DataFrame(results)
71
+
72
+ # Generate Sleek Interactive Plotly Graph
73
+ fig = go.Figure()
 
74
 
75
+ # The Flawed Standard Model Line (Gray/Blue)
76
+ fig.add_trace(go.Scatter(
77
+ x=dates, y=raw_temps,
78
+ mode='lines+markers',
79
+ name='Bronze 118 (Standard)',
80
+ line=dict(color='#64748b', width=2, dash='dot'),
81
+ marker=dict(size=6)
82
+ ))
83
+
84
+ # The Gold 121 Stabilized Trajectory (Bright Cyan/Teal)
85
+ fig.add_trace(go.Scatter(
86
+ x=dates, y=fixed_temps,
87
+ mode='lines+markers',
88
+ name='Gold 121 (Stabilized)',
89
+ line=dict(color='#06b6d4', width=4),
90
+ marker=dict(size=10, symbol='diamond')
91
+ ))
92
+
93
+ fig.update_layout(
94
+ title=f"Prediction Drift Analysis: {loc_name}",
95
+ xaxis_title="Date",
96
+ yaxis_title="Max Temperature (°F)",
97
+ template="plotly_dark",
98
+ plot_bgcolor="rgba(0,0,0,0)",
99
+ paper_bgcolor="rgba(0,0,0,0)",
100
+ margin=dict(l=20, r=20, t=50, b=20),
101
+ legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
102
+ )
103
+
104
+ return fig, df
105
+
106
+ # 4. SLEEK CUSTOM GUI BUILD
107
+ # Using a custom theme with rounded Quicksand font and dark slate colors
108
+ custom_theme = gr.themes.Base(
109
+ primary_hue="cyan",
110
+ neutral_hue="slate",
111
+ font=[gr.themes.GoogleFont("Quicksand"), "sans-serif"],
112
+ ).set(
113
+ body_background_fill="*neutral_950",
114
+ body_text_color="*neutral_50",
115
+ block_background_fill="*neutral_900",
116
+ block_border_width="1px",
117
+ block_border_color="*neutral_800",
118
+ button_primary_background_fill="*primary_600",
119
+ input_background_fill="*neutral_800",
120
+ )
121
+
122
+ with gr.Blocks(theme=custom_theme) as demo:
123
+ gr.Markdown("# 🛰️ Samaran Kernel: Pro V2")
124
+ gr.Markdown("### Advanced Atmospheric Drift Stabilization & Visualization")
125
 
126
+ with gr.Row():
127
+ loc_input = gr.Textbox(label="Target Location", placeholder="Enter Zip (e.g., 88220) or City", scale=4)
128
+ submit_btn = gr.Button("Initialize Vector Execution", variant="primary", scale=1)
129
+
130
+ # Multi-Tab Professional Interface
131
+ with gr.Tabs():
132
+ with gr.Tab("🌍 Surface Trajectory"):
133
+ plot_output = gr.Plot(label="Drift Visualization Matrix")
134
+ table_output = gr.Dataframe(headers=["Date", "Raw Model (Bronze 118)", "Kernel Fixed (Gold 121)", "Drift Applied"])
135
+
136
+ with gr.Tab("🌪️ Jet Stream Twist (Feature_004)"):
137
+ gr.Markdown("### Zonal & Meridional Velocity Diagnostics")
138
+ gr.Markdown("*Module awaiting Feature_004 dataset linkage.*")
139
+
140
+ with gr.Tab("✅ Ground Truth (ROC)"):
141
+ gr.Markdown("### Historical Validation & Accuracy Matrix")
142
+ gr.Markdown("*Module awaiting hindcast API integration.*")
143
+
144
+ # Actions
145
+ submit_btn.click(fn=generate_pro_dashboard, inputs=loc_input, outputs=[plot_output, table_output])
146
+ loc_input.submit(fn=generate_pro_dashboard, inputs=loc_input, outputs=[plot_output, table_output])
147
 
148
  # Execute
149
  demo.launch()