aiwhisperer33 commited on
Commit
d32d511
·
verified ·
1 Parent(s): eeaaac0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -61
app.py CHANGED
@@ -3,75 +3,91 @@ import pandas as pd
3
  import numpy as np
4
  from scipy.fft import fft, fftfreq
5
  from sklearn.preprocessing import MinMaxScaler
6
- from tensorflow.keras.models import Sequential, load_model
7
- import requests
 
8
 
9
- # --- Pre-trained Model (Simple LSTM) ---
10
- def build_model():
11
- model = Sequential([
12
- tf.keras.layers.LSTM(32, input_shape=(30, 1)),
13
- tf.keras.layers.Dense(1)
14
- ])
15
- model.compile(loss='mse', optimizer='adam')
16
- return model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- # --- Core Functions ---
19
- def analyze_data(data_url, prediction_days=30):
20
  try:
21
- # 1. Fetch data
22
- df = pd.read_csv(data_url)
23
- dates = df.columns[4:] # COVID data format
24
- values = df.drop(columns=['Province/State', 'Country/Region', 'Lat', 'Long']).sum(axis=0)[4:].values.astype(float)
25
 
26
- # 2. Detect cycles
27
- N = len(values)
28
- yf = fft(values)
29
  xf = fftfreq(N, 1)[:N//2]
30
- dominant_freq = xf[np.argmax(np.abs(yf[0:N//2]))]
31
- cycle_days = int(1/dominant_freq)
32
-
33
- # 3. Make predictions (simplified)
34
- scaler = MinMaxScaler()
35
- scaled = scaler.fit_transform(values.reshape(-1, 1))
36
-
37
- model = build_model()
38
- model.fit(scaled[:-10], scaled[10:], epochs=5, verbose=0) # Quick training
39
-
40
- preds = model.predict(scaled[-30:].reshape(1, 30, 1))
41
- preds = scaler.inverse_transform(preds).flatten().tolist()
42
 
43
- # 4. Generate insights
44
- insights = [
45
- f"Dominant cycle: {cycle_days} days",
46
- f"Next {prediction_days}-day trend: {'↑ Upward' if preds[-1] > preds[0] else '↓ Downward'}",
47
- "Action: Monitor closely around cycle peaks"
48
- ]
49
 
50
- # Simple plot
51
- plot = pd.DataFrame({
52
- 'Historical': values,
53
- 'Predicted': [None]*(len(values)) + preds
54
- }).plot(title="Cases Analysis").figure
 
 
55
 
56
- return plot, insights
57
-
58
  except Exception as e:
59
- return None, [f"Error: {str(e)}"]
60
 
61
- # --- Gradio Interface ---
62
- interface = gr.Interface(
63
- fn=analyze_data,
64
- inputs=[
65
- gr.Textbox(label="Data URL",
66
- value="https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/data/time_series_covid19_confirmed_global.csv"),
67
- gr.Number(label="Days to Predict", value=30)
68
- ],
69
- outputs=[
70
- gr.Plot(label="Analysis"),
71
- gr.JSON(label="Insights")
72
- ],
73
- title="DeepSeek Lite Analyzer",
74
- description="Analyze time-series data from public URLs. Works best with COVID-19 format data."
75
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- interface.launch()
 
 
3
  import numpy as np
4
  from scipy.fft import fft, fftfreq
5
  from sklearn.preprocessing import MinMaxScaler
6
+ from tensorflow.keras.models import Sequential
7
+ from tensorflow.keras.layers import LSTM, Dense
8
+ import matplotlib.pyplot as plt
9
 
10
+ def load_data(input_source):
11
+ """Handle both uploaded files and URLs"""
12
+ if isinstance(input_source, str) and input_source.startswith("http"):
13
+ # Load from URL
14
+ df = pd.read_csv(
15
+ input_source,
16
+ engine='python',
17
+ on_bad_lines='warn',
18
+ encoding='utf-8'
19
+ )
20
+ else:
21
+ # Load from uploaded file
22
+ df = pd.read_csv(
23
+ input_source.name,
24
+ engine='python',
25
+ on_bad_lines='warn',
26
+ encoding='utf-8'
27
+ )
28
+
29
+ # Common cleaning steps
30
+ df = df.drop(columns=['Province/State', 'Lat', 'Long'], errors='ignore')
31
+ df = df.groupby('Country/Region').sum().T
32
+ df.index = pd.to_datetime(df.index)
33
+ df['Global'] = df.sum(axis=1)
34
+ return df['Global'].diff().fillna(0)
35
 
36
+ def analyze_data(input_source):
 
37
  try:
38
+ data = load_data(input_source)
 
 
 
39
 
40
+ # Analysis logic
41
+ N = len(data)
42
+ yf = fft(data.values)
43
  xf = fftfreq(N, 1)[:N//2]
44
+ cycle_days = int(1/xf[np.argmax(np.abs(yf[0:N//2]))])
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ # Create plot
47
+ fig, ax = plt.subplots()
48
+ ax.plot(data.index, data.values)
49
+ ax.set_title("COVID-19 Daily New Cases Analysis")
 
 
50
 
51
+ return (
52
+ f"🔮 Analysis Results:\n"
53
+ f"- Cycle: {cycle_days} days\n"
54
+ f"- Latest 30-day average: {data[-30:].mean():.1f} cases/day\n"
55
+ f"- Current trend: {'↑ Rising' if data[-1] > data[-7] else '↓ Falling'}",
56
+ fig
57
+ )
58
 
 
 
59
  except Exception as e:
60
+ return f"Error: {str(e)}", None
61
 
62
+ # Create hybrid interface with chat and file upload
63
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
64
+ gr.Markdown("# 📊 Data Analysis Bot")
65
+ gr.Markdown("Upload a CSV file or paste a COVID data URL")
66
+
67
+ with gr.Row():
68
+ with gr.Column():
69
+ file_upload = gr.File(label="Upload CSV", file_count=1)
70
+ url_input = gr.Textbox(label="Or paste URL here")
71
+ submit_btn = gr.Button("Analyze")
72
+ with gr.Column():
73
+ chat = gr.Chatbot(height=400)
74
+ plot_output = gr.Plot()
75
+
76
+ # Handle both input methods
77
+ submit_btn.click(
78
+ fn=analyze_data,
79
+ inputs=[gr.combine(file_upload, url_input)],
80
+ outputs=[chat, plot_output]
81
+ )
82
+
83
+ # Example inputs
84
+ gr.Examples(
85
+ examples=[
86
+ ["https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/data/time_series_covid19_confirmed_global.csv"],
87
+ ["sample_data.csv"] # Upload this via Hugging Face
88
+ ],
89
+ inputs=[url_input]
90
+ )
91
 
92
+ if __name__ == "__main__":
93
+ app.launch()