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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -152
app.py CHANGED
@@ -70,7 +70,6 @@
70
 
71
 
72
  #####################
73
-
74
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
75
  import datetime
76
  import requests
@@ -80,169 +79,89 @@ 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
  """특정 시간대의 현재 시간을 알려주는 도구입니다.
@@ -256,7 +175,17 @@ def get_current_time_in_timezone(timezone: str) -> str:
256
  except Exception as e:
257
  return f"'{timezone}' 시간대 정보를 가져오는 중 오류 발생: {str(e)}"
258
 
259
- # 메인 Agent 설정
 
 
 
 
 
 
 
 
 
 
260
  final_answer = FinalAnswerTool()
261
 
262
  model = HfApiModel(
@@ -266,44 +195,48 @@ model = HfApiModel(
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()
 
70
 
71
 
72
  #####################
 
73
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
74
  import datetime
75
  import requests
 
79
  from tools.final_answer import FinalAnswerTool
80
  from Gradio_UI import GradioUI
81
 
82
+ # 날씨 정보 조회 도구 (더미 데이터 사용)
83
  @tool
84
+ def get_weather_info(city: str) -> str:
85
  """특정 도시의 현재 날씨 정보를 가져오는 도구입니다.
86
  Args:
87
  city: 도시명 (예: 'Seoul', 'Busan')
 
88
  """
89
  try:
90
+ # 실제 API 대신 더미 데이터 사용 (테스트용)
91
+ dummy_weather_data = {
92
+ "seoul": {"temp": 15, "condition": "흐림", "humidity": 65, "wind": 3.2},
93
+ "busan": {"temp": 18, "condition": "맑음", "humidity": 70, "wind": 2.8},
94
+ "incheon": {"temp": 13, "condition": "비", "humidity": 80, "wind": 4.1},
95
+ "daegu": {"temp": 20, "condition": "맑음", "humidity": 45, "wind": 1.5},
96
+ "gwangju": {"temp": 17, "condition": "구름많음", "humidity": 55, "wind": 2.0}
97
+ }
 
 
 
 
 
 
 
 
 
 
 
98
 
99
+ city_lower = city.lower()
100
+ if city_lower in dummy_weather_data:
101
+ data = dummy_weather_data[city_lower]
102
+ result = f"{city} 날씨 정보:\n"
103
+ result += f"🌡️ 기온: {data['temp']}°C\n"
104
+ result += f"☁️ 날씨: {data['condition']}\n"
105
+ result += f"💧 습도: {data['humidity']}%\n"
106
+ result += f"💨 바람: {data['wind']}m/s"
107
+ return result
 
 
108
  else:
109
+ return f"{city}의 날씨 정보를 찾을 수 없습니다. 사용 가능한 도시: Seoul, Busan, Incheon, Daegu, Gwangju"
110
 
111
  except Exception as e:
112
  return f"날씨 정보 조회 중 오류 발생: {str(e)}"
113
 
114
  # 옷차림 추천 도구
115
  @tool
116
+ def recommend_outfit(temperature: int, weather_condition: str) -> str:
117
+ """기온과 날씨 상태를 바탕으로 옷차림을 추천하는 도구입니다.
118
  Args:
119
+ temperature: 기온 (섭씨)
120
+ weather_condition: 날씨 상태 (예: '맑음', '비', '흐림')
121
  """
122
  try:
123
+ recommendations = []
 
 
 
 
 
 
 
 
124
  accessories = []
125
 
126
+ # 기온별 기본 추천
127
+ if temperature <= 5:
128
+ recommendations = ["두꺼운 코트나 패딩", "긴팔 내의", "긴바지", "부츠"]
129
+ accessories = ["목도리", "장갑", "모자"]
130
+ elif temperature <= 15:
131
+ recommendations = ["자켓이나 코트", "긴팔 셔츠", "긴바지", "운동화"]
132
+ accessories = ["가벼운 목도리"]
133
+ elif temperature <= 25:
134
+ recommendations = ["가디건이나 얇은 자켓", "긴팔 또는 반팔", "긴바지", "운동화"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  else:
136
+ recommendations = ["반팔 티셔츠", "반바지나 얇은 바지", "샌들이나 운동화"]
 
 
 
 
 
137
 
138
+ # 날씨별 추가 아이템
139
+ if "비" in weather_condition:
140
+ accessories.append("우산")
141
+ accessories.append("방수 재킷")
142
 
143
+ result = f"🌡️ {temperature}°C, {weather_condition} 날씨 추천 옷차림:\n\n"
144
+ result += "👔 기본 옷차림:\n"
145
+ for item in recommendations:
146
+ result += f" • {item}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
+ if accessories:
149
+ result += "\n🎒 추가 아이템:\n"
150
+ for item in accessories:
151
+ result += f" • {item}\n"
 
 
 
 
 
152
 
153
+ # 온도별 팁
154
+ if temperature <= 5:
155
+ result += "\n❄️ 매우 추우니 보온에 신경 쓰세요!"
156
+ elif temperature >= 28:
157
+ result += "\n☀️ 더우니 통풍이 잘 되는 옷을 선택하세요!"
158
 
159
+ return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
  except Exception as e:
162
+ return f"옷차림 추천 중 오류 발생: {str(e)}"
163
 
164
+ # 시간대별 현재 시간 조회 (기존 도구)
165
  @tool
166
  def get_current_time_in_timezone(timezone: str) -> str:
167
  """특정 시간대의 현재 시간을 알려주는 도구입니다.
 
175
  except Exception as e:
176
  return f"'{timezone}' 시간대 정보를 가져오는 중 오류 발생: {str(e)}"
177
 
178
+ # 사용자 정의 도구 예시 (기존 템플릿 유지)
179
+ @tool
180
+ def my_custom_tool(arg1: str, arg2: int) -> str:
181
+ """아직 아무 기능이 없는 도구입니다
182
+ Args:
183
+ arg1: 첫 번째 인수
184
+ arg2: 두 번째 인수
185
+ """
186
+ return "어떤 마법을 만들어 보실 건가요?"
187
+
188
+ # Agent 설정
189
  final_answer = FinalAnswerTool()
190
 
191
  model = HfApiModel(
 
195
  custom_role_conversions=None,
196
  )
197
 
198
+ # Hub에서 도구 불러오기 (선택사항)
199
  try:
200
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
201
+ print("이미지 생성 도구 로드 성공!")
202
+ except Exception as e:
203
  image_generation_tool = None
204
+ print(f"이미지 생성 도구 로드 실패: {e}")
 
 
 
205
 
206
  with open("prompts.yaml", 'r') as stream:
207
  prompt_templates = yaml.safe_load(stream)
208
 
209
+ # 도구 목록 설정
210
  tools_list = [
211
  final_answer,
212
  get_weather_info,
213
+ recommend_outfit,
 
214
  get_current_time_in_timezone,
215
+ my_custom_tool
216
  ]
217
 
218
+ # 이미지 생성 도구가 로드되었다면 추가
219
  if image_generation_tool:
220
  tools_list.append(image_generation_tool)
221
 
222
+ # DuckDuckGo 검색 도구 추가 (선택사항)
223
+ try:
224
+ search_tool = DuckDuckGoSearchTool()
225
+ tools_list.append(search_tool)
226
+ print("검색 도구 추가 성공!")
227
+ except Exception as e:
228
+ print(f"검색 도구 추가 실패: {e}")
229
+
230
  agent = CodeAgent(
231
  model=model,
232
  tools=tools_list,
233
+ max_steps=6,
234
  verbosity_level=1,
235
  grammar=None,
236
  planning_interval=None,
237
+ name=None, # name을 None으로 설정하여 오류 방지
238
+ description=None,
239
  prompt_templates=prompt_templates
240
  )
241
 
 
242
  GradioUI(agent).launch()