mwill-AImission commited on
Commit
adb3e6b
·
verified ·
1 Parent(s): 4469dae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -31
app.py CHANGED
@@ -1,94 +1,141 @@
 
 
1
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
- import datetime
3
- import requests
4
- import yaml
5
- from tools.final_answer import FinalAnswerTool
6
- from Gradio_UI import GradioUI
7
 
8
- # Tool for commenting code in simple language
 
 
 
9
  @tool
10
  def comment_code(code: str) -> str:
11
- """A tool that takes a block of code as input and returns the same code with comments explaining each part in simple terms.
 
 
 
12
  Args:
13
  code: The input code as a string.
14
  """
15
  try:
16
- # Use a basic approach to add comments above each line
17
  commented_code = ""
 
18
  for line in code.split('\n'):
19
- stripped = line.strip()
20
  if stripped:
 
21
  if "def " in stripped:
22
  commented_code += "# This defines a function\n"
 
23
  elif "import " in stripped:
24
  commented_code += "# Importing necessary modules\n"
 
25
  elif "for " in stripped or "while " in stripped:
26
  commented_code += "# Looping through values\n"
 
27
  elif "if " in stripped:
28
  commented_code += "# Checking a condition\n"
 
29
  elif "return " in stripped:
30
  commented_code += "# Returning a value from the function\n"
 
31
  commented_code += line + "\n"
32
  return commented_code
33
  except Exception as e:
 
34
  return f"Error processing code: {str(e)}"
35
 
36
- # Tool for extracting code from an image (screenshot)
 
 
 
37
  @tool
38
  def extract_code_from_image(image_path: str) -> str:
39
- """Extracts text from an image file (screenshot) that contains code.
 
 
40
  Args:
41
  image_path: The path to the image file.
42
  """
43
  try:
44
- from PIL import Image
45
- import pytesseract
46
- image = Image.open(image_path)
47
- code_text = pytesseract.image_to_string(image)
48
  return code_text
49
  except Exception as e:
 
50
  return f"Error extracting code from image: {str(e)}"
51
 
52
- # Tool for reading code from a file
 
 
 
53
  @tool
54
  def extract_code_from_file(file_path: str) -> str:
55
- """Reads code text from a file.
 
 
56
  Args:
57
  file_path: The path to the file containing code.
58
  """
59
  try:
60
- with open(file_path, 'r') as f:
61
- code_text = f.read()
62
  return code_text
63
  except Exception as e:
 
64
  return f"Error reading code from file: {str(e)}"
65
 
 
66
  final_answer = FinalAnswerTool()
67
 
 
 
 
 
68
  model = HfApiModel(
69
- max_tokens=2096,
70
- temperature=0.5,
71
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
72
- custom_role_conversions=None,
73
  )
74
 
75
- # Import additional tool from Hub (if needed)
 
 
 
76
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
77
 
 
 
 
 
78
  with open("prompts.yaml", 'r') as stream:
79
  prompt_templates = yaml.safe_load(stream)
80
 
 
 
 
 
81
  agent = CodeAgent(
82
  model=model,
83
  tools=[final_answer, comment_code, extract_code_from_image, extract_code_from_file],
84
- max_steps=6,
85
- verbosity_level=1,
86
- grammar=None,
87
- planning_interval=None,
88
- name="Code Commenter",
89
  description="An agent that adds explanatory comments to code in simple terms.",
90
- prompt_templates=prompt_templates
91
  )
92
 
 
 
 
 
93
  GradioUI(agent).launch()
94
-
 
1
+ # Importing necessary modules and tools for our application.
2
+ # These libraries help us work with code, dates, files, images, and the user interface.
3
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
4
+ import datetime # Helps with dates and times.
5
+ import requests # Lets us make web requests.
6
+ import yaml # Reads YAML files, which are used for configuration.
7
+ from tools.final_answer import FinalAnswerTool # Custom tool to finalize the answer.
8
+ from Gradio_UI import GradioUI # Module for creating a simple web interface.
9
 
10
+ # -----------------------------
11
+ # Tool: comment_code
12
+ # -----------------------------
13
+ # This function takes a piece of code and adds comments to explain what each part does.
14
  @tool
15
  def comment_code(code: str) -> str:
16
+ """
17
+ A tool that takes a block of code and returns the same code with added comments.
18
+ The comments explain each part of the code in simple terms.
19
+
20
  Args:
21
  code: The input code as a string.
22
  """
23
  try:
24
+ # Start with an empty string to collect our commented code.
25
  commented_code = ""
26
+ # Split the code into lines so we can process each line separately.
27
  for line in code.split('\n'):
28
+ stripped = line.strip() # Remove extra spaces from the beginning and end.
29
  if stripped:
30
+ # Check if the line defines a function.
31
  if "def " in stripped:
32
  commented_code += "# This defines a function\n"
33
+ # Check if the line imports a module.
34
  elif "import " in stripped:
35
  commented_code += "# Importing necessary modules\n"
36
+ # Check if the line is a loop (for or while).
37
  elif "for " in stripped or "while " in stripped:
38
  commented_code += "# Looping through values\n"
39
+ # Check if the line contains a conditional statement.
40
  elif "if " in stripped:
41
  commented_code += "# Checking a condition\n"
42
+ # Check if the line returns a value.
43
  elif "return " in stripped:
44
  commented_code += "# Returning a value from the function\n"
45
+ # Add the original code line after the comment.
46
  commented_code += line + "\n"
47
  return commented_code
48
  except Exception as e:
49
+ # If something goes wrong, return an error message.
50
  return f"Error processing code: {str(e)}"
51
 
52
+ # -----------------------------
53
+ # Tool: extract_code_from_image
54
+ # -----------------------------
55
+ # This tool extracts text (code) from an image file, like a screenshot.
56
  @tool
57
  def extract_code_from_image(image_path: str) -> str:
58
+ """
59
+ Extracts text from an image file (a screenshot) that contains code.
60
+
61
  Args:
62
  image_path: The path to the image file.
63
  """
64
  try:
65
+ from PIL import Image # Module for opening and working with images.
66
+ import pytesseract # OCR tool to extract text from images.
67
+ image = Image.open(image_path) # Open the image file.
68
+ code_text = pytesseract.image_to_string(image) # Extract text from the image.
69
  return code_text
70
  except Exception as e:
71
+ # Return an error message if extraction fails.
72
  return f"Error extracting code from image: {str(e)}"
73
 
74
+ # -----------------------------
75
+ # Tool: extract_code_from_file
76
+ # -----------------------------
77
+ # This tool reads code from a file and returns it as text.
78
  @tool
79
  def extract_code_from_file(file_path: str) -> str:
80
+ """
81
+ Reads code text from a file.
82
+
83
  Args:
84
  file_path: The path to the file containing code.
85
  """
86
  try:
87
+ with open(file_path, 'r') as f: # Open the file in read mode.
88
+ code_text = f.read() # Read the content of the file.
89
  return code_text
90
  except Exception as e:
91
+ # Return an error message if the file cannot be read.
92
  return f"Error reading code from file: {str(e)}"
93
 
94
+ # Create an instance of the FinalAnswerTool.
95
  final_answer = FinalAnswerTool()
96
 
97
+ # -----------------------------
98
+ # Set up the language model.
99
+ # -----------------------------
100
+ # This model will help the agent understand and process code-related tasks.
101
  model = HfApiModel(
102
+ max_tokens=2096, # Maximum tokens the model can output.
103
+ temperature=0.5, # Controls randomness in the model's output.
104
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct', # Specific model to use.
105
+ custom_role_conversions=None, # No custom role conversion needed here.
106
  )
107
 
108
+ # -----------------------------
109
+ # Optionally, load an image generation tool.
110
+ # -----------------------------
111
+ # This tool is loaded from an external source, though it isn't used directly here.
112
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
113
 
114
+ # -----------------------------
115
+ # Load prompt templates from a configuration file.
116
+ # -----------------------------
117
+ # This file likely contains text instructions that help guide the agent.
118
  with open("prompts.yaml", 'r') as stream:
119
  prompt_templates = yaml.safe_load(stream)
120
 
121
+ # -----------------------------
122
+ # Set up the CodeAgent.
123
+ # -----------------------------
124
+ # The agent uses the model and the tools to perform tasks.
125
  agent = CodeAgent(
126
  model=model,
127
  tools=[final_answer, comment_code, extract_code_from_image, extract_code_from_file],
128
+ max_steps=6, # Limit on how many steps the agent can take.
129
+ verbosity_level=1, # Level of detail in the logs/output.
130
+ grammar=None, # No special grammar rules are applied.
131
+ planning_interval=None, # No specific planning interval set.
132
+ name="Code Commenter", # Name of the agent.
133
  description="An agent that adds explanatory comments to code in simple terms.",
134
+ prompt_templates=prompt_templates # Prompts to guide the agent's responses.
135
  )
136
 
137
+ # -----------------------------
138
+ # Launch the Gradio user interface.
139
+ # -----------------------------
140
+ # Gradio creates a simple web interface for users to interact with the agent.
141
  GradioUI(agent).launch()