borjasoutoprego commited on
Commit
713c665
·
verified ·
1 Parent(s): 3d1237b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -36
app.py CHANGED
@@ -1,65 +1,88 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
- import datetime
3
- import requests
4
- import pytz
 
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
-
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
  Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
  """
19
- return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
24
  Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
26
  """
27
  try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
33
- except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
 
 
 
 
 
 
 
35
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  final_answer = FinalAnswerTool()
38
  model = HfApiModel(
39
- max_tokens=2096,
40
- temperature=0.5,
41
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
42
- custom_role_conversions=None,
43
  )
44
 
45
-
46
- # Import tool from Hub
47
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
48
-
49
  with open("prompts.yaml", 'r') as stream:
50
  prompt_templates = yaml.safe_load(stream)
51
-
52
  agent = CodeAgent(
53
  model=model,
54
- tools=[final_answer], ## add your tools here (don't remove final answer)
55
  max_steps=6,
56
  verbosity_level=1,
57
  grammar=None,
58
  planning_interval=None,
59
- name=None,
60
- description=None,
61
  prompt_templates=prompt_templates
62
  )
63
 
64
-
65
- GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, HfApiModel, load_tool, tool
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ import io
5
+ import base64
6
  import yaml
7
  from tools.final_answer import FinalAnswerTool
 
8
  from Gradio_UI import GradioUI
9
 
 
10
  @tool
11
+ def load_and_summarize_data(file: bytes, filename: str) -> str:
12
+ """Loads a CSV/Excel file from user input and generates a summary.
 
13
  Args:
14
+ file: The uploaded file in bytes.
15
+ filename: The original file name to determine format.
16
  """
17
+ try:
18
+ if filename.endswith('.csv'):
19
+ df = pd.read_csv(io.BytesIO(file))
20
+ elif filename.endswith('.xlsx'):
21
+ df = pd.read_excel(io.BytesIO(file))
22
+ else:
23
+ return "Unsupported format. Please upload a CSV or Excel file."
24
+
25
+ summary = df.describe().to_string()
26
+ return f"Dataset Summary:\n{summary}"
27
+
28
+ except Exception as e:
29
+ return f"Error processing the file: {str(e)}"
30
 
31
  @tool
32
+ def generate_basic_charts(file: bytes, filename: str) -> str:
33
+ """Generates basic charts from an uploaded CSV/Excel file.
34
  Args:
35
+ file: The uploaded file in bytes.
36
+ filename: The original file name to determine format.
37
  """
38
  try:
39
+ if filename.endswith('.csv'):
40
+ df = pd.read_csv(io.BytesIO(file))
41
+ elif filename.endswith('.xlsx'):
42
+ df = pd.read_excel(io.BytesIO(file))
43
+ else:
44
+ return "Unsupported format. Please upload a CSV or Excel file."
45
+
46
+ img_paths = []
47
+ for column in df.select_dtypes(include=['number']).columns[:3]: # Limit to 3 charts
48
+ plt.figure()
49
+ df[column].hist(bins=20)
50
+ plt.title(f"Distribution of {column}")
51
+ plt.xlabel(column)
52
+ plt.ylabel("Frequency")
53
 
54
+ img_buf = io.BytesIO()
55
+ plt.savefig(img_buf, format="png")
56
+ img_buf.seek(0)
57
+ img_str = base64.b64encode(img_buf.getvalue()).decode("utf-8")
58
+ img_paths.append(f'<img src="data:image/png;base64,{img_str}" />')
59
+
60
+ return "Generated Charts:\n" + "\n".join(img_paths)
61
+
62
+ except Exception as e:
63
+ return f"Error generating charts: {str(e)}"
64
 
65
  final_answer = FinalAnswerTool()
66
  model = HfApiModel(
67
+ max_tokens=2096,
68
+ temperature=0.5,
69
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
70
+ custom_role_conversions=None,
71
  )
72
 
 
 
 
 
73
  with open("prompts.yaml", 'r') as stream:
74
  prompt_templates = yaml.safe_load(stream)
75
+
76
  agent = CodeAgent(
77
  model=model,
78
+ tools=[final_answer, load_and_summarize_data, generate_basic_charts], # Updated to support file upload
79
  max_steps=6,
80
  verbosity_level=1,
81
  grammar=None,
82
  planning_interval=None,
83
+ name="Data Report Assistant",
84
+ description="An agent that processes uploaded CSV/Excel files, generates summaries, and visualizations.",
85
  prompt_templates=prompt_templates
86
  )
87
 
88
+ GradioUI(agent).launch()