manikantachary18 commited on
Commit
a81ca9e
·
verified ·
1 Parent(s): 258bf23

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -76
app.py CHANGED
@@ -1,27 +1,29 @@
1
  import gradio as gr
2
  import pandas as pd
3
  import plotly.express as px
4
- import requests
5
  import io
 
6
 
7
- # Global DataFrame to store loaded data
8
  df_global = pd.DataFrame()
9
 
10
- # Load data from uploaded file
11
  def load_data(file):
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.name)
17
- elif ext in ['xls', 'xlsx']:
18
- return pd.read_excel(file.name)
19
- elif ext == 'json':
20
- return pd.read_json(file.name)
 
 
 
21
  return pd.DataFrame()
22
 
23
- # Load data from URL
24
- def load_url_data(url):
25
  try:
26
  response = requests.get(url)
27
  response.raise_for_status()
@@ -32,98 +34,67 @@ def load_url_data(url):
32
  elif url.endswith(".xlsx") or url.endswith(".xls"):
33
  return pd.read_excel(io.BytesIO(response.content))
34
  except Exception as e:
35
- print(f"Error loading from URL: {e}")
36
  return pd.DataFrame()
37
 
38
- # Process the uploaded file or URL
39
  def process_inputs(file, url):
40
  global df_global
 
41
 
42
- try:
43
- if url:
44
- df = load_url_data(url)
45
- elif file:
46
- df = load_data(file)
47
- else:
48
- return pd.DataFrame(), gr.update(choices=[], value=None), gr.update(choices=[], value=None)
49
-
50
- if df.empty:
51
- return pd.DataFrame(), gr.update(choices=[], value=None), gr.update(choices=[], value=None)
52
-
53
- df_global = df
54
-
55
- all_cols = list(df.columns)
56
- numeric_cols = list(df.select_dtypes(include='number').columns)
57
 
58
- default_x = all_cols[0] if all_cols else None
59
- default_y = numeric_cols[0] if numeric_cols else None
 
60
 
61
- return df.head(), gr.update(choices=all_cols, value=default_x), gr.update(choices=numeric_cols, value=default_y)
 
62
 
63
- except Exception as e:
64
- print("Error processing inputs:", e)
65
- return pd.DataFrame(), gr.update(choices=[], value=None), gr.update(choices=[], value=None)
66
 
67
- # Create the plot
68
- def update_plot(chart_type, x_col, y_col):
69
  global df_global
70
- if df_global.empty or x_col is None or y_col is None:
71
  return None
72
 
73
  try:
74
  if chart_type == "Bar Chart":
75
- fig = px.bar(df_global, x=x_col, y=y_col)
76
  elif chart_type == "Line Chart":
77
- fig = px.line(df_global, x=x_col, y=y_col)
78
  elif chart_type == "Scatter Plot":
79
- fig = px.scatter(df_global, x=x_col, y=y_col)
80
  elif chart_type == "Pie Chart":
81
- fig = px.pie(df_global, names=x_col, values=y_col)
82
  elif chart_type == "Box Plot":
83
- fig = px.box(df_global, x=x_col, y=y_col)
84
- else:
85
- return None
86
- return fig
87
  except Exception as e:
88
  print("Plot error:", e)
89
  return None
90
 
91
- # Gradio UI
92
  with gr.Blocks() as demo:
93
- gr.Markdown("## 📊 Data Visualization App")
94
 
95
  with gr.Row():
96
  file_input = gr.File(file_types=[".csv", ".xlsx", ".json"], label="Upload File")
97
- url_input = gr.Textbox(label="Or paste a file URL")
98
-
99
- load_button = gr.Button("Load Data")
100
-
101
- dataframe_output = gr.Dataframe(label="Data Preview", interactive=False)
102
-
103
- chart_type = gr.Dropdown(
104
- ["Bar Chart", "Line Chart", "Scatter Plot", "Pie Chart", "Box Plot"],
105
- label="Chart Type"
106
- )
107
- x_col = gr.Dropdown(label="X-axis")
108
- y_col = gr.Dropdown(label="Y-axis")
109
 
110
- generate_button = gr.Button("Generate Chart")
111
- plot_output = gr.Plot(label="Generated Chart")
112
 
113
- # Button functionality
114
- load_button.click(
115
- fn=process_inputs,
116
- inputs=[file_input, url_input],
117
- outputs=[dataframe_output, x_col, y_col]
118
- )
119
 
120
- generate_button.click(
121
- fn=update_plot,
122
- inputs=[chart_type, x_col, y_col],
123
- outputs=plot_output
124
- )
125
 
126
- # Run the app
127
  if __name__ == "__main__":
128
  demo.launch()
129
 
 
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.name)
17
+ elif ext in ['xls', 'xlsx']:
18
+ return pd.read_excel(file.name)
19
+ elif ext == 'json':
20
+ return pd.read_json(file.name)
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()
 
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 both file and URL
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
 
48
+ df_global = df
49
+ all_cols = list(df.columns)
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
+ # Plot
58
+ def update_plot(chart_type, x, y):
59
  global df_global
60
+ if df_global.empty:
61
  return None
62
 
63
  try:
64
  if chart_type == "Bar Chart":
65
+ return px.bar(df_global, x=x, y=y)
66
  elif chart_type == "Line Chart":
67
+ return px.line(df_global, x=x, y=y)
68
  elif chart_type == "Scatter Plot":
69
+ return px.scatter(df_global, x=x, y=y)
70
  elif chart_type == "Pie Chart":
71
+ return px.pie(df_global, names=x, values=y)
72
  elif chart_type == "Box Plot":
73
+ return px.box(df_global, x=x, y=y)
 
 
 
74
  except Exception as e:
75
  print("Plot error:", e)
76
  return None
77
 
 
78
  with gr.Blocks() as demo:
79
+ gr.Markdown("## 📊 Clean Data Visualizer")
80
 
81
  with gr.Row():
82
  file_input = gr.File(file_types=[".csv", ".xlsx", ".json"], label="Upload File")
83
+ url_input = gr.Textbox(label="Or enter file URL")
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ load_button = gr.Button("Load")
 
86
 
87
+ df_preview = gr.Dataframe(label="Preview", interactive=False)
88
+ x_dropdown = gr.Dropdown(label="X-axis")
89
+ y_dropdown = gr.Dropdown(label="Y-axis")
90
+ chart_type = gr.Dropdown(["Bar Chart", "Line Chart", "Scatter Plot", "Pie Chart", "Box Plot"], label="Chart Type")
91
+ plot_area = gr.Plot(label="Chart")
92
+ generate_button = gr.Button("Generate Plot")
93
 
94
+ # Event hooks
95
+ load_button.click(process_inputs, inputs=[file_input, url_input], outputs=[df_preview, x_dropdown, y_dropdown])
96
+ generate_button.click(update_plot, inputs=[chart_type, x_dropdown, y_dropdown], outputs=plot_area)
 
 
97
 
 
98
  if __name__ == "__main__":
99
  demo.launch()
100