Spaces:
Runtime error
Runtime error
Update app.py
Browse files
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
|
| 7 |
-
import
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
def analyze_data(data_url, prediction_days=30):
|
| 20 |
try:
|
| 21 |
-
|
| 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 |
-
#
|
| 27 |
-
N = len(
|
| 28 |
-
yf = fft(values)
|
| 29 |
xf = fftfreq(N, 1)[:N//2]
|
| 30 |
-
|
| 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 |
-
#
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
"Action: Monitor closely around cycle peaks"
|
| 48 |
-
]
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
return plot, insights
|
| 57 |
-
|
| 58 |
except Exception as e:
|
| 59 |
-
return
|
| 60 |
|
| 61 |
-
#
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
gr.
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
gr.
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
|
|
|
|
|
|
| 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()
|