aiwhisperer33 commited on
Commit
6d0b9a1
ยท
verified ยท
1 Parent(s): 161d1fb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -44
app.py CHANGED
@@ -1,3 +1,7 @@
 
 
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
@@ -9,84 +13,101 @@ 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__":
 
1
+ # app.py
2
+ import os
3
+ os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0' # Suppress TensorFlow warnings
4
+
5
  import gradio as gr
6
  import pandas as pd
7
  import numpy as np
 
13
 
14
  def load_data(input_source):
15
  """Handle both uploaded files and URLs"""
16
+ try:
17
+ if isinstance(input_source, str) and input_source.startswith("http"):
18
+ # Load from URL
19
+ df = pd.read_csv(
20
+ input_source,
21
+ engine='python',
22
+ on_bad_lines='warn',
23
+ encoding='utf-8'
24
+ )
25
+ else:
26
+ # Load from uploaded file
27
+ df = pd.read_csv(
28
+ input_source.name,
29
+ engine='python',
30
+ on_bad_lines='warn',
31
+ encoding='utf-8'
32
+ )
33
+
34
+ # Common cleaning steps
35
+ df = df.drop(columns=['Province/State', 'Lat', 'Long'], errors='ignore')
36
+ df = df.groupby('Country/Region').sum().T
37
+ df.index = pd.to_datetime(df.index)
38
+ df['Global'] = df.sum(axis=1)
39
+ return df['Global'].diff().fillna(0)
40
 
41
+ except Exception as e:
42
+ raise ValueError(f"Data loading failed: {str(e)}")
 
 
 
 
43
 
44
  def analyze_data(input_source):
45
  try:
46
+ if not input_source:
47
+ return "โš ๏ธ Please upload a file or enter a URL", None
48
+
49
  data = load_data(input_source)
50
 
51
+ # Cycle detection
52
  N = len(data)
53
  yf = fft(data.values)
54
  xf = fftfreq(N, 1)[:N//2]
55
  cycle_days = int(1/xf[np.argmax(np.abs(yf[0:N//2]))])
56
 
57
  # Create plot
58
+ fig, ax = plt.subplots(figsize=(10, 4))
59
+ ax.plot(data.index, data.values, label='Daily Cases')
60
+ ax.set_title("COVID-19 Analysis")
61
+ ax.set_xlabel("Date")
62
+ ax.set_ylabel("New Cases")
63
+ ax.grid(True)
64
+ plt.tight_layout()
65
+
66
+ # Generate insights
67
+ latest_avg = data[-30:].mean()
68
+ trend = "โ†‘ Rising" if data[-1] > data[-7] else "โ†“ Falling"
69
 
70
  return (
71
+ f"๐Ÿ” Analysis Results:\n"
72
+ f"- Dominant Cycle: {cycle_days} days\n"
73
+ f"- 30-Day Average: {latest_avg:.1f} cases/day\n"
74
+ f"- Current Trend: {trend}\n"
75
+ f"โœ… Analysis completed successfully!",
76
  fig
77
  )
78
 
79
  except Exception as e:
80
  return f"โŒ Error: {str(e)}", None
81
 
82
+ # Create interface
83
  with gr.Blocks(theme=gr.themes.Soft()) as app:
84
+ gr.Markdown("# ๐Ÿฆ  COVID-19 Analysis Bot")
85
+ gr.Markdown("Analyze case data from URLs or uploaded CSV files")
86
 
87
  with gr.Row():
88
  with gr.Column():
89
+ file_upload = gr.File(label="1. Upload CSV", file_count='single')
90
+ url_input = gr.Textbox(label="2. Or paste data URL here")
91
+ submit_btn = gr.Button("Analyze โž”")
92
+
93
  with gr.Column():
94
+ chat_output = gr.Chatbot(label="Analysis Results", height=300)
95
+ plot_output = gr.Plot(label="Case Trend")
96
 
97
+ # Link components
98
  submit_btn.click(
99
  fn=analyze_data,
100
  inputs=[gr.combine(file_upload, url_input)],
101
+ outputs=[chat_output, plot_output]
102
  )
103
 
104
+ # Examples
105
  gr.Examples(
106
  examples=[
107
+ ["https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/data/time_series_covid19_confirmed_global.csv"]
 
108
  ],
109
+ inputs=[url_input],
110
+ label="Try this example URL:"
111
  )
112
 
113
  if __name__ == "__main__":