HaiderAUT commited on
Commit
dbe8f3a
·
verified ·
1 Parent(s): 9289741

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -16
app.py CHANGED
@@ -5,6 +5,9 @@ import yaml
5
  from tools.final_answer import FinalAnswerTool
6
  from Gradio_UI import GradioUI
7
 
 
 
 
8
  # Import replicate directly to generate images using Stable Diffusion.
9
  try:
10
  import replicate
@@ -16,7 +19,7 @@ def my_custom_tool(arg1: str, arg2: int) -> str:
16
  """
17
  A tool that shares interesting facts about Chakwal, highlighting its flora, fauna, natural landscapes,
18
  and cultural heritage. It also shows the current local time in Chakwal (Asia/Karachi timezone).
19
-
20
  Args:
21
  arg1: A custom note or additional message to include in the output.
22
  arg2: The number of detailed facts to include about Chakwal (1 to 4).
@@ -60,7 +63,7 @@ def my_custom_tool(arg1: str, arg2: int) -> str:
60
  def get_current_time_in_timezone(timezone: str) -> str:
61
  """
62
  A tool that fetches the current local time in a specified timezone.
63
-
64
  Args:
65
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
66
  """
@@ -77,12 +80,14 @@ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_co
77
 
78
  # ── NEW TOOL: prompte_chakwal ──
79
  @tool
80
- def prompte_chakwal(custom_note: str = "", num_results: int = 3) -> str:
81
  """
82
  A tool that promotes Chakwal by retrieving real-time information and generating promotional images.
83
  It provides the current local time, live news about Chakwal from DuckDuckGo, and creates images that
84
- highlight the city's natural beauty and vibrant culture using two different image generators.
85
-
 
 
86
  Args:
87
  custom_note: A custom note to add a specific theme to the generated images.
88
  num_results: The maximum number of real-time search results (news/information) to include.
@@ -93,7 +98,7 @@ def prompte_chakwal(custom_note: str = "", num_results: int = 3) -> str:
93
  try:
94
  tz = pytz.timezone("Asia/Karachi")
95
  current_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
96
- output_lines.append(f"Current local time in Chakwal: {current_time}")
97
  except Exception as e:
98
  output_lines.append("Error fetching current time in Chakwal.")
99
 
@@ -103,13 +108,13 @@ def prompte_chakwal(custom_note: str = "", num_results: int = 3) -> str:
103
  search_results = duck_tool.run(query)
104
 
105
  if isinstance(search_results, list):
106
- output_lines.append("\nReal-Time News and Information:")
107
  for i, result in enumerate(search_results[:num_results]):
108
  title = result.get("title", "No Title")
109
  snippet = result.get("snippet", "No description available")
110
- output_lines.append(f"{i+1}. {title}: {snippet}")
111
  elif isinstance(search_results, str):
112
- output_lines.append("\nReal-Time News and Information:")
113
  output_lines.append(search_results)
114
  else:
115
  output_lines.append("\nNo real-time information available.")
@@ -119,24 +124,35 @@ def prompte_chakwal(custom_note: str = "", num_results: int = 3) -> str:
119
  if custom_note:
120
  image_prompt += f". Theme: {custom_note}"
121
 
122
- generated_image = image_generation_tool(image_prompt)
123
- output_lines.append("\nGenerated Promotional Image (smolagents):")
124
- output_lines.append(f"{generated_image}")
125
 
126
  # 4. Generate a promotional image using the Replicate API (Stable Diffusion) if available.
 
127
  if replicate:
128
  try:
129
  stable_diffusion = replicate.models.get("stability-ai/stable-diffusion")
130
  # The predict method typically returns a list of image URLs.
131
- generated_image_replicate = stable_diffusion.predict(prompt=image_prompt)
132
- output_lines.append("\nGenerated Promotional Image (Replicate):")
133
- output_lines.append(f"{generated_image_replicate}")
 
 
 
 
134
  except Exception as e:
135
  output_lines.append(f"\nError generating image with Replicate: {e}")
136
  else:
137
  output_lines.append("\nReplicate module is not available. Install it via 'pip install replicate'.")
138
 
139
- return "\n".join(output_lines)
 
 
 
 
 
 
140
 
141
 
142
  # Set up the final answer tool.
 
5
  from tools.final_answer import FinalAnswerTool
6
  from Gradio_UI import GradioUI
7
 
8
+ # Import AgentText to return a composite Markdown message
9
+ from smolagents.agent_types import AgentText
10
+
11
  # Import replicate directly to generate images using Stable Diffusion.
12
  try:
13
  import replicate
 
19
  """
20
  A tool that shares interesting facts about Chakwal, highlighting its flora, fauna, natural landscapes,
21
  and cultural heritage. It also shows the current local time in Chakwal (Asia/Karachi timezone).
22
+
23
  Args:
24
  arg1: A custom note or additional message to include in the output.
25
  arg2: The number of detailed facts to include about Chakwal (1 to 4).
 
63
  def get_current_time_in_timezone(timezone: str) -> str:
64
  """
65
  A tool that fetches the current local time in a specified timezone.
66
+
67
  Args:
68
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
69
  """
 
80
 
81
  # ── NEW TOOL: prompte_chakwal ──
82
  @tool
83
+ def prompte_chakwal(custom_note: str = "", num_results: int = 3) -> AgentText:
84
  """
85
  A tool that promotes Chakwal by retrieving real-time information and generating promotional images.
86
  It provides the current local time, live news about Chakwal from DuckDuckGo, and creates images that
87
+ highlight the city's natural beauty and vibrant culture.
88
+
89
+ The final output is a composite Markdown message that includes text details and an embedded image.
90
+
91
  Args:
92
  custom_note: A custom note to add a specific theme to the generated images.
93
  num_results: The maximum number of real-time search results (news/information) to include.
 
98
  try:
99
  tz = pytz.timezone("Asia/Karachi")
100
  current_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
101
+ output_lines.append(f"**Current local time in Chakwal:** {current_time}")
102
  except Exception as e:
103
  output_lines.append("Error fetching current time in Chakwal.")
104
 
 
108
  search_results = duck_tool.run(query)
109
 
110
  if isinstance(search_results, list):
111
+ output_lines.append("\n**Real-Time News and Information:**")
112
  for i, result in enumerate(search_results[:num_results]):
113
  title = result.get("title", "No Title")
114
  snippet = result.get("snippet", "No description available")
115
+ output_lines.append(f"{i+1}. **{title}**: {snippet}")
116
  elif isinstance(search_results, str):
117
+ output_lines.append("\n**Real-Time News and Information:**")
118
  output_lines.append(search_results)
119
  else:
120
  output_lines.append("\nNo real-time information available.")
 
124
  if custom_note:
125
  image_prompt += f". Theme: {custom_note}"
126
 
127
+ generated_image_url = image_generation_tool(image_prompt)
128
+ output_lines.append("\n**Generated Promotional Image (smolagents):**")
129
+ output_lines.append(f"Image URL: {generated_image_url}")
130
 
131
  # 4. Generate a promotional image using the Replicate API (Stable Diffusion) if available.
132
+ generated_image_replicate = None
133
  if replicate:
134
  try:
135
  stable_diffusion = replicate.models.get("stability-ai/stable-diffusion")
136
  # The predict method typically returns a list of image URLs.
137
+ result = stable_diffusion.predict(prompt=image_prompt)
138
+ if isinstance(result, list) and len(result) > 0:
139
+ generated_image_replicate = result[0]
140
+ else:
141
+ generated_image_replicate = result
142
+ output_lines.append("\n**Generated Promotional Image (Replicate):**")
143
+ output_lines.append(f"Image URL: {generated_image_replicate}")
144
  except Exception as e:
145
  output_lines.append(f"\nError generating image with Replicate: {e}")
146
  else:
147
  output_lines.append("\nReplicate module is not available. Install it via 'pip install replicate'.")
148
 
149
+ # Choose one image to embed: Prefer the Replicate image if available, else the smolagents image.
150
+ final_image_url = generated_image_replicate if generated_image_replicate else generated_image_url
151
+
152
+ # Create a composite Markdown with text details and embed the chosen image.
153
+ composite_markdown = "\n".join(output_lines) + f"\n\n![Chakwal Promotional Image]({final_image_url})"
154
+
155
+ return AgentText(composite_markdown)
156
 
157
 
158
  # Set up the final answer tool.