manikantachary18 commited on
Commit
b4fc6fa
Β·
verified Β·
1 Parent(s): dd7291c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -73
app.py CHANGED
@@ -1,41 +1,47 @@
1
  import gradio as gr
2
  import pandas as pd
3
  import plotly.express as px
 
 
4
 
5
- # Global dataframe
6
  df_global = pd.DataFrame()
7
 
 
8
  def load_data(file):
9
- if file is None:
10
- return pd.DataFrame()
11
  try:
12
- if file.name.endswith(".csv"):
13
- return pd.read_csv(file.name)
14
- elif file.name.endswith(".xlsx"):
15
- return pd.read_excel(file.name)
16
- elif file.name.endswith(".json"):
17
- return pd.read_json(file.name)
 
 
 
18
  except Exception as e:
19
  print("File load error:", e)
20
- return pd.DataFrame()
21
 
 
22
  def load_url(url):
23
- if not url:
24
- return pd.DataFrame()
25
  try:
 
 
26
  if url.endswith(".csv"):
27
- return pd.read_csv(url)
28
- elif url.endswith(".xlsx"):
29
- return pd.read_excel(url)
30
  elif url.endswith(".json"):
31
- return pd.read_json(url)
 
 
32
  except Exception as e:
33
  print("URL load error:", e)
34
- return pd.DataFrame()
35
 
 
36
  def process_inputs(file, url):
37
  global df_global
38
  df = load_url(url) if url else load_data(file)
 
39
  if df.empty:
40
  return pd.DataFrame(), gr.update(choices=[], value=None), gr.update(choices=[], value=None)
41
 
@@ -44,76 +50,90 @@ def process_inputs(file, url):
44
  num_cols = list(df.select_dtypes(include="number").columns)
45
 
46
  default_x = all_cols[0] if all_cols else None
47
- default_y = num_cols[0] if num_cols else (all_cols[0] if all_cols else None)
48
 
49
- return (
50
- df.head(),
51
- gr.update(choices=all_cols, value=default_x),
52
- gr.update(choices=num_cols if num_cols else all_cols, value=default_y)
53
- )
54
 
55
- def smart_update(chart_type, x, y):
 
56
  global df_global
57
  if df_global.empty:
58
- return None, gr.Textbox.update(value="No data loaded.", visible=True)
59
-
60
  try:
61
- if chart_type == "Summary":
62
- summary = df_global.describe(include="all").to_string()
63
- return None, gr.Textbox.update(value=summary, visible=True)
64
-
65
- if not x or not y:
66
- return None, gr.Textbox.update(value="Please select both X and Y axes.", visible=True)
67
-
68
  if chart_type == "Bar Chart":
69
- return px.bar(df_global, x=x, y=y), gr.Textbox.update(visible=False)
70
  elif chart_type == "Line Chart":
71
- return px.line(df_global, x=x, y=y), gr.Textbox.update(visible=False)
72
  elif chart_type == "Scatter Plot":
73
- return px.scatter(df_global, x=x, y=y), gr.Textbox.update(visible=False)
74
  elif chart_type == "Pie Chart":
75
- return px.pie(df_global, names=x, values=y), gr.Textbox.update(visible=False)
76
  elif chart_type == "Box Plot":
77
- return px.box(df_global, x=x, y=y), gr.Textbox.update(visible=False)
78
- else:
79
- return None, gr.Textbox.update(value="Unsupported chart type.", visible=True)
80
-
81
  except Exception as e:
82
- return None, gr.Textbox.update(value=str(e), visible=True)
83
-
84
- with gr.Blocks(theme=gr.themes.Base(primary_hue="blue")) as enhanced_ui:
85
- gr.Markdown("""
86
- # ✨ Animated Data Visualizer
87
- Welcome to your interactive data analysis tool!
88
- Upload your dataset and explore visual insights like never before.
89
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  with gr.Row():
92
- with gr.Column(scale=2):
93
- file_input = gr.File(label="πŸ“‚ Upload Data File", file_types=[".csv", ".xlsx", ".json"])
94
- url_input = gr.Textbox(label="πŸ”— Or paste file URL", placeholder="https://example.com/data.csv")
95
- with gr.Column(scale=1):
96
- chart_type = gr.Dropdown(
97
- ["Summary", "Bar Chart", "Line Chart", "Scatter Plot", "Pie Chart", "Box Plot"],
98
- label="πŸ“ˆ Chart Type",
99
- info="Select type of visualization"
100
- )
101
- generate_button = gr.Button("πŸš€ Generate", variant="primary")
102
-
103
- with gr.Accordion("πŸ“Š Data Preview and Settings", open=True):
104
- df_preview = gr.Dataframe(label="Preview", interactive=False)
105
- with gr.Row():
106
- x_dropdown = gr.Dropdown(label="X-axis", interactive=True)
107
- y_dropdown = gr.Dropdown(label="Y-axis", interactive=True)
108
 
109
- with gr.Row():
110
- plot_area = gr.Plot(label="πŸ–ΌοΈ Chart Output")
111
- summary_box = gr.Textbox(label="πŸ“‹ Summary", visible=False, lines=15)
 
 
 
 
 
112
 
113
- # Link callbacks
114
- file_input.change(process_inputs, inputs=[file_input, url_input], outputs=[df_preview, x_dropdown, y_dropdown])
115
- url_input.change(process_inputs, inputs=[file_input, url_input], outputs=[df_preview, x_dropdown, y_dropdown])
116
- generate_button.click(smart_update, inputs=[chart_type, x_dropdown, y_dropdown], outputs=[plot_area, summary_box])
117
 
118
  if __name__ == "__main__":
119
- enhanced_ui.launch()
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import plotly.express as px
4
+ import io
5
+ import requests
6
 
 
7
  df_global = pd.DataFrame()
8
 
9
+ # Load from file
10
  def load_data(file):
 
 
11
  try:
12
+ if file is None:
13
+ return pd.DataFrame()
14
+ ext = file.name.split('.')[-1]
15
+ if ext == 'csv':
16
+ return pd.read_csv(file.file)
17
+ elif ext in ['xls', 'xlsx']:
18
+ return pd.read_excel(file.file)
19
+ elif ext == 'json':
20
+ return pd.read_json(file.file)
21
  except Exception as e:
22
  print("File load error:", e)
23
+ return pd.DataFrame()
24
 
25
+ # Load from URL
26
  def load_url(url):
 
 
27
  try:
28
+ response = requests.get(url)
29
+ response.raise_for_status()
30
  if url.endswith(".csv"):
31
+ return pd.read_csv(io.StringIO(response.text))
 
 
32
  elif url.endswith(".json"):
33
+ return pd.read_json(io.StringIO(response.text))
34
+ elif url.endswith(".xlsx") or url.endswith(".xls"):
35
+ return pd.read_excel(io.BytesIO(response.content))
36
  except Exception as e:
37
  print("URL load error:", e)
38
+ return pd.DataFrame()
39
 
40
+ # Process inputs
41
  def process_inputs(file, url):
42
  global df_global
43
  df = load_url(url) if url else load_data(file)
44
+
45
  if df.empty:
46
  return pd.DataFrame(), gr.update(choices=[], value=None), gr.update(choices=[], value=None)
47
 
 
50
  num_cols = list(df.select_dtypes(include="number").columns)
51
 
52
  default_x = all_cols[0] if all_cols else None
53
+ default_y = num_cols[0] if num_cols else None
54
 
55
+ return df.head(), gr.update(choices=all_cols, value=default_x), gr.update(choices=num_cols, value=default_y)
 
 
 
 
56
 
57
+ # Update plot
58
+ def update_plot(chart_type, x, y):
59
  global df_global
60
  if df_global.empty:
61
+ return None
 
62
  try:
 
 
 
 
 
 
 
63
  if chart_type == "Bar Chart":
64
+ return px.bar(df_global, x=x, y=y)
65
  elif chart_type == "Line Chart":
66
+ return px.line(df_global, x=x, y=y)
67
  elif chart_type == "Scatter Plot":
68
+ return px.scatter(df_global, x=x, y=y)
69
  elif chart_type == "Pie Chart":
70
+ return px.pie(df_global, names=x, values=y)
71
  elif chart_type == "Box Plot":
72
+ return px.box(df_global, x=x, y=y)
 
 
 
73
  except Exception as e:
74
+ print("Plot error:", e)
75
+ return None
76
+
77
+ # Animated UI
78
+ with gr.Blocks(css="""
79
+ body {
80
+ margin: 0;
81
+ padding: 0;
82
+ font-family: 'Segoe UI', sans-serif;
83
+ color: white;
84
+ }
85
+ #bg {
86
+ position: fixed;
87
+ width: 100%;
88
+ height: 100%;
89
+ background: linear-gradient(-45deg, #1e3c72, #2a5298, #1e3c72);
90
+ background-size: 400% 400%;
91
+ animation: gradient 15s ease infinite;
92
+ z-index: -1;
93
+ }
94
+ @keyframes gradient {
95
+ 0% { background-position: 0% 50%; }
96
+ 50% { background-position: 100% 50%; }
97
+ 100% { background-position: 0% 50%; }
98
+ }
99
+ .animate-fade {
100
+ animation: fadeInUp 1s ease-in-out;
101
+ }
102
+ @keyframes fadeInUp {
103
+ from {
104
+ opacity: 0;
105
+ transform: translateY(20px);
106
+ }
107
+ to {
108
+ opacity: 1;
109
+ transform: translateY(0);
110
+ }
111
+ }
112
+ """) as demo:
113
+
114
+ gr.HTML('<div id="bg"></div>') # Background animation
115
+
116
+ gr.Markdown("## ✨ Thunder BI β€” Animated Data Visualizer", elem_classes="animate-fade")
117
 
118
  with gr.Row():
119
+ with gr.Column():
120
+ file_input = gr.File(file_types=[".csv", ".xlsx", ".json"], label="πŸ“ Upload File", elem_classes="animate-fade")
121
+ url_input = gr.Textbox(label="🌐 Or enter file URL", elem_classes="animate-fade")
122
+ load_button = gr.Button("πŸ”„ Load", elem_classes="animate-fade")
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
+ with gr.Column():
125
+ chart_type = gr.Dropdown(["Bar Chart", "Line Chart", "Scatter Plot", "Pie Chart", "Box Plot"], label="πŸ“Š Chart Type", elem_classes="animate-fade")
126
+ x_dropdown = gr.Dropdown(label="X-axis", elem_classes="animate-fade")
127
+ y_dropdown = gr.Dropdown(label="Y-axis", elem_classes="animate-fade")
128
+ generate_button = gr.Button("πŸš€ Generate Plot", elem_classes="animate-fade")
129
+
130
+ plot_area = gr.Plot(label="Chart", elem_classes="animate-fade")
131
+ df_preview = gr.Dataframe(label="Preview", interactive=False, elem_classes="animate-fade")
132
 
133
+ # Event handlers
134
+ load_button.click(process_inputs, inputs=[file_input, url_input], outputs=[df_preview, x_dropdown, y_dropdown])
135
+ generate_button.click(update_plot, inputs=[chart_type, x_dropdown, y_dropdown], outputs=plot_area)
 
136
 
137
  if __name__ == "__main__":
138
+ demo.launch()
139
+