pavanmutha commited on
Commit
d3f8ea6
·
verified ·
1 Parent(s): c553e84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -117
app.py CHANGED
@@ -1,28 +1,13 @@
 
1
 
2
-
3
- import gradio as gr
4
- from smolagents import HfApiModel, CodeAgent
5
- from huggingface_hub import login
6
- import os
7
- import shutil
8
-
9
- from huggingface_hub import login
10
-
11
- # Add this before model initialization
12
- hf_token = os.getenv("HF_TOKEN")
13
- login(token=hf_token, add_to_git_credential=True)
14
-
15
- # Then create model with explicit token
16
- model = HfApiModel(
17
- "mistralai/Mixtral-8x7B-Instruct-v0.1",
18
- token=hf_token # Pass token explicitly
19
- )
20
-
21
- # Add this formatting function
22
  def format_analysis_report(raw_output, visuals):
23
  try:
24
- # Convert string output to dictionary
25
- analysis_dict = ast.literal_eval(str(raw_output))
 
 
 
 
26
 
27
  report = f"""
28
  <div style="font-family: Arial, sans-serif; padding: 20px; color: #333;">
@@ -40,98 +25,6 @@ def format_analysis_report(raw_output, visuals):
40
  </div>
41
  """
42
  return report, visuals
43
- except:
44
- return raw_output, visuals
45
-
46
- def format_observations(observations):
47
- items = []
48
- for key, value in observations.items():
49
- if 'proportions' in key:
50
- items.append(f"""
51
- <div style="margin: 15px 0; padding: 15px; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
52
- <h3 style="margin: 0 0 10px 0; color: #4A708B;">{key.replace('_', ' ').title()}</h3>
53
- <pre style="margin: 0; padding: 10px; background: #f8f9fa; border-radius: 4px;">{value}</pre>
54
- </div>
55
- """)
56
- return '\n'.join(items)
57
-
58
- def format_insights(insights, visuals):
59
- items = []
60
- for idx, (key, insight) in enumerate(insights.items()):
61
- img_tag = ""
62
- if idx < len(visuals):
63
- img_tag = f'<img src="/file={visuals[idx]}" style="max-width: 100%; height: auto; margin-top: 10px; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">'
64
-
65
- items.append(f"""
66
- <div style="margin: 20px 0; padding: 20px; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
67
- <div style="display: flex; align-items: center; gap: 10px;">
68
- <div style="background: #2B547E; color: white; width: 30px; height: 30px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">{idx+1}</div>
69
- <p style="margin: 0; font-size: 16px;">{insight}</p>
70
- </div>
71
- {img_tag}
72
- </div>
73
- """)
74
- return '\n'.join(items)
75
-
76
- def analyze_data(csv_file, additional_notes=""):
77
- # Clear previous figures
78
- if os.path.exists('./figures'):
79
- shutil.rmtree('./figures')
80
- os.makedirs('./figures', exist_ok=True)
81
-
82
- # Initialize model and agent
83
- model = HfApiModel("mistralai/Mixtral-8x7B-Instruct-v0.1") # Best overall
84
- agent = CodeAgent(
85
- tools=[],
86
- model=model,
87
- additional_authorized_imports=[
88
- "numpy",
89
- "pandas",
90
- "matplotlib.pyplot",
91
- "seaborn"
92
- ],
93
- )
94
- # Run analysis
95
- analysis_result = agent.run(
96
- """You are an expert data analyst. Perform comprehensive analysis including:
97
- 1. Basic statistics and data quality checks
98
- 2. 3 insightful analytical questions about relationships in the data
99
- 3. Visualization of key patterns and correlations
100
- 4. Actionable real-world insights derived from findings
101
-
102
- Generate publication-quality visualizations and save to './figures/'
103
- """,
104
- additional_args={
105
- "additional_notes": additional_notes,
106
- "source_file": csv_file
107
- }
108
- )
109
-
110
- # Collect generated visuals
111
- visuals = [os.path.join('./figures', f) for f in os.listdir('./figures')
112
- if f.endswith(('.png', '.jpg', '.jpeg'))]
113
-
114
-
115
- return format_analysis_report(analysis_result, visuals)
116
-
117
- # Create Gradio interface
118
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
119
- gr.Markdown("## 📊 AI Data Analysis Agent")
120
-
121
- with gr.Row():
122
- with gr.Column():
123
- file_input = gr.File(label="Upload CSV Dataset", type="filepath")
124
- notes_input = gr.Textbox(label="Dataset Notes (Optional)", lines=3)
125
- analyze_btn = gr.Button("Analyze", variant="primary")
126
-
127
- with gr.Column():
128
- analysis_output = gr.Markdown("### Analysis results will appear here...")
129
- gallery = gr.Gallery(label="Data Visualizations", columns=2)
130
-
131
- analyze_btn.click(
132
- fn=analyze_data,
133
- inputs=[file_input, notes_input],
134
- outputs=[analysis_output, gallery]
135
- )
136
-
137
- demo.launch(debug=True)
 
1
+ import ast
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  def format_analysis_report(raw_output, visuals):
4
  try:
5
+ # Check if raw_output is already a dictionary
6
+ if isinstance(raw_output, dict):
7
+ analysis_dict = raw_output
8
+ else:
9
+ # If it's a string, try to convert it to a dictionary
10
+ analysis_dict = ast.literal_eval(str(raw_output))
11
 
12
  report = f"""
13
  <div style="font-family: Arial, sans-serif; padding: 20px; color: #333;">
 
25
  </div>
26
  """
27
  return report, visuals
28
+ except Exception as e:
29
+ print(f"Error formatting report: {e}")
30
+ return raw_output, visuals