realizedr commited on
Commit
8e2cafd
·
verified ·
1 Parent(s): 8c5c24b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +271 -31
app.py CHANGED
@@ -1,69 +1,309 @@
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
 
39
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
-
42
  model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
  )
48
 
 
 
 
 
 
 
49
 
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
 
53
  with open("prompts.yaml", 'r') as stream:
54
  prompt_templates = yaml.safe_load(stream)
55
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  agent = CodeAgent(
57
  model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
- max_steps=6,
60
  verbosity_level=1,
61
  grammar=None,
62
  planning_interval=None,
63
- name=None,
64
- description=None,
65
  prompt_templates=prompt_templates
66
  )
67
 
68
-
69
  GradioUI(agent).launch()
 
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
+
39
+ # # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
+ # # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
+
42
+ # model = HfApiModel(
43
+ # max_tokens=2096,
44
+ # temperature=0.5,
45
+ # model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
+ # custom_role_conversions=None,
47
+ # )
48
+
49
+
50
+ # # Import tool from Hub
51
+ # image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
+
53
+ # with open("prompts.yaml", 'r') as stream:
54
+ # prompt_templates = yaml.safe_load(stream)
55
+
56
+ # agent = CodeAgent(
57
+ # model=model,
58
+ # tools=[final_answer], ## add your tools here (don't remove final answer)
59
+ # max_steps=6,
60
+ # verbosity_level=1,
61
+ # grammar=None,
62
+ # planning_interval=None,
63
+ # name=None,
64
+ # description=None,
65
+ # prompt_templates=prompt_templates
66
+ # )
67
+
68
+
69
+ # GradioUI(agent).launch()
70
+
71
+
72
+ #####################
73
+
74
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
75
  import datetime
76
  import requests
77
  import pytz
78
  import yaml
79
+ import json
80
  from tools.final_answer import FinalAnswerTool
 
81
  from Gradio_UI import GradioUI
82
 
83
+ # 날씨 정보 조회 도구
84
+ @tool
85
+ def get_weather_info(city: str, country: str = "KR") -> str:
86
+ """특정 도시의 현재 날씨 정보를 가져오는 도구입니다.
87
+ Args:
88
+ city: 도시명 (예: 'Seoul', 'Busan')
89
+ country: 국가 코드 (기본값: 'KR')
90
+ """
91
+ try:
92
+ # OpenWeatherMap API 사용 (무료 API 키 필요)
93
+ # 실제 사용시 API_KEY를 발급받아 사용하세요
94
+ API_KEY = "your_openweather_api_key_here" # 실제 API 키로 교체 필요
95
+
96
+ # API 키가 없는 경우 더미 데이터 반환
97
+ if API_KEY == "your_openweather_api_key_here":
98
+ # 서울 기준 더미 데이터
99
+ dummy_weather = {
100
+ "temperature": 15,
101
+ "feels_like": 13,
102
+ "humidity": 65,
103
+ "weather": "흐림",
104
+ "wind_speed": 3.2,
105
+ "city": city
106
+ }
107
+ return json.dumps(dummy_weather, ensure_ascii=False)
108
+
109
+ url = f"http://api.openweathermap.org/data/2.5/weather?q={city},{country}&appid={API_KEY}&units=metric&lang=kr"
110
+ response = requests.get(url, timeout=10)
111
+
112
+ if response.status_code == 200:
113
+ data = response.json()
114
+ weather_info = {
115
+ "city": data["name"],
116
+ "temperature": data["main"]["temp"],
117
+ "feels_like": data["main"]["feels_like"],
118
+ "humidity": data["main"]["humidity"],
119
+ "weather": data["weather"][0]["description"],
120
+ "wind_speed": data["wind"]["speed"]
121
+ }
122
+ return json.dumps(weather_info, ensure_ascii=False)
123
+ else:
124
+ return f"날씨 정보를 가져올 수 없습니다. 도시명을 확인해주세요: {city}"
125
+
126
+ except Exception as e:
127
+ return f"날씨 정보 조회 중 오류 발생: {str(e)}"
128
+
129
+ # 옷차림 추천 도구
130
  @tool
131
+ def recommend_outfit(weather_data: str) -> str:
132
+ """날씨 정보를 바탕으로 적절한 옷차림을 추천하는 도구입니다.
 
133
  Args:
134
+ weather_data: JSON 형태의 날씨 정보 문자열
 
135
  """
136
+ try:
137
+ weather = json.loads(weather_data)
138
+ temp = weather.get("temperature", 20)
139
+ feels_like = weather.get("feels_like", temp)
140
+ humidity = weather.get("humidity", 50)
141
+ weather_desc = weather.get("weather", "맑음").lower()
142
+ wind_speed = weather.get("wind_speed", 0)
143
+
144
+ # 기온별 기본 추천
145
+ outfit_recommendations = []
146
+ accessories = []
147
+
148
+ if temp <= 0:
149
+ outfit_recommendations = [
150
+ "두꺼운 패딩이나 코트",
151
+ "기모 내의",
152
+ "털 안감 바지",
153
+ "방한화",
154
+ "두꺼운 양말"
155
+ ]
156
+ accessories = ["목도리", "장갑", "모자", "마스크"]
157
+
158
+ elif temp <= 10:
159
+ outfit_recommendations = [
160
+ "코트나 자켓",
161
+ "긴팔 셔츠나 스웨터",
162
+ "긴바지",
163
+ "운동화나 부츠"
164
+ ]
165
+ accessories = ["목도리", "가벼운 장갑"]
166
+
167
+ elif temp <= 20:
168
+ outfit_recommendations = [
169
+ "가디건이나 얇은 자켓",
170
+ "긴팔 티셔츠",
171
+ "긴바지나 청바지",
172
+ "운동화"
173
+ ]
174
+
175
+ elif temp <= 28:
176
+ outfit_recommendations = [
177
+ "반팔 티셔츠나 얇은 셔츠",
178
+ "면바지나 청바지",
179
+ "운동화나 캔버스화"
180
+ ]
181
+
182
+ else:
183
+ outfit_recommendations = [
184
+ "반팔 티셔츠나 민소매",
185
+ "반바지나 얇은 바지",
186
+ "샌들이나 운동화",
187
+ "통풍이 잘 되는 옷"
188
+ ]
189
+
190
+ # 날씨 상황별 추가 고려사항
191
+ special_notes = []
192
+
193
+ if "비" in weather_desc or "shower" in weather_desc:
194
+ accessories.extend(["우산", "방수 재킷"])
195
+ special_notes.append("비가 올 예정이니 우산을 챙기세요!")
196
+
197
+ if "눈" in weather_desc or "snow" in weather_desc:
198
+ accessories.extend(["방수 신발", "장갑"])
199
+ special_notes.append("눈이 올 예정이니 미끄럼 방지 신발을 신으세요!")
200
+
201
+ if wind_speed > 5:
202
+ special_notes.append("바람이 강하니 바람막이나 바람이 잘 통하지 않는 옷을 입으세요!")
203
+
204
+ if humidity > 80:
205
+ special_notes.append("습도가 높으니 통풍이 잘 되는 소재의 옷을 선택하세요!")
206
+
207
+ # 체감온도 고려
208
+ if abs(temp - feels_like) > 3:
209
+ if feels_like < temp:
210
+ special_notes.append(f"체감온도({feels_like}°C)가 실제 온도보다 낮으니 조금 더 따뜻하게 입으세요!")
211
+ else:
212
+ special_notes.append(f"체감온도({feels_like}°C)가 실제 온도보다 높으니 조금 더 시원하게 입으세요!")
213
+
214
+ # 결과 정리
215
+ result = {
216
+ "temperature": temp,
217
+ "weather_condition": weather_desc,
218
+ "recommended_clothes": outfit_recommendations,
219
+ "accessories": accessories,
220
+ "special_notes": special_notes,
221
+ "general_tip": f"{temp}°C 날씨에 적합한 옷차림입니다."
222
+ }
223
+
224
+ return json.dumps(result, ensure_ascii=False)
225
+
226
+ except Exception as e:
227
+ return f"옷차림 추천 중 오류 발생: {str(e)}"
228
 
229
+ # 패션 스타일 이미지 생성 도구
230
+ @tool
231
+ def generate_outfit_image(outfit_description: str) -> str:
232
+ """추천된 옷차림에 대한 스타일 이미지를 생성하는 도구입니다.
233
+ Args:
234
+ outfit_description: 옷차림 설명 텍스트
235
+ """
236
+ try:
237
+ # 실제로는 이미지 생성 API를 호출하거나 image_generation_tool을 사용
238
+ # 여기서는 설명만 반환
239
+ prompt = f"A stylish person wearing {outfit_description}, fashion photography, clean background, good lighting"
240
+ return f"이미지 생성 프롬프트: {prompt}\n(실제 구현시 이미지 생성 도구를 사용하여 이미지를 생성합니다)"
241
+
242
+ except Exception as e:
243
+ return f"이미지 생성 중 오류 발생: {str(e)}"
244
+
245
+ # 시간대별 날씨 조회 도구 (기존 도구 개선)
246
  @tool
247
  def get_current_time_in_timezone(timezone: str) -> str:
248
+ """특정 시간대의 현재 시간을 알려주는 도구입니다.
249
  Args:
250
+ timezone: 유효한 시간대를 나타내는 문자열(예: 'Asia/Seoul').
251
  """
252
  try:
 
253
  tz = pytz.timezone(timezone)
 
254
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
255
+ return f"{timezone}의 현재 시간은 {local_time}입니다"
256
  except Exception as e:
257
+ return f"'{timezone}' 시간대 정보를 가져오는 중 오류 발생: {str(e)}"
 
258
 
259
+ # 메인 Agent 설정
260
  final_answer = FinalAnswerTool()
261
 
 
 
 
262
  model = HfApiModel(
263
+ max_tokens=2096,
264
+ temperature=0.5,
265
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
266
+ custom_role_conversions=None,
267
  )
268
 
269
+ # Hub에서 이미지 생성 도구 로드 (실제 이미지 생성용)
270
+ try:
271
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
272
+ except:
273
+ image_generation_tool = None
274
+ print("이미지 생성 도구를 로드할 수 없습니다. 텍스트 설명만 제공됩니다.")
275
 
276
+ # 검색 도구
277
+ search_tool = DuckDuckGoSearchTool()
278
 
279
  with open("prompts.yaml", 'r') as stream:
280
  prompt_templates = yaml.safe_load(stream)
281
+
282
+ # 모든 도구를 포함한 Agent 생성
283
+ tools_list = [
284
+ final_answer,
285
+ get_weather_info,
286
+ recommend_outfit,
287
+ generate_outfit_image,
288
+ get_current_time_in_timezone,
289
+ search_tool
290
+ ]
291
+
292
+ # 이미지 생성 도구가 있다면 추가
293
+ if image_generation_tool:
294
+ tools_list.append(image_generation_tool)
295
+
296
  agent = CodeAgent(
297
  model=model,
298
+ tools=tools_list,
299
+ max_steps=8, # 더 많은 단계 허용
300
  verbosity_level=1,
301
  grammar=None,
302
  planning_interval=None,
303
+ name="Weather Fashion Assistant",
304
+ description="날씨 정보를 바탕으로 적절한 옷차림을 추천하는 AI 어시스턴트",
305
  prompt_templates=prompt_templates
306
  )
307
 
308
+ # Gradio UI 실행
309
  GradioUI(agent).launch()