vladd19 commited on
Commit
6f5a8b1
·
verified ·
1 Parent(s): 0f42e34

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -52
app.py CHANGED
@@ -16,66 +16,30 @@ from smolagents.agent_types import AgentImage
16
  from PIL import Image
17
 
18
  @tool
19
- def generate_image(
20
- prompt: str,
21
- negative_prompt: str = "blurry, text, watermark, low quality",
22
- width: int = 1024,
23
- height: int = 1024
24
- ) -> AgentImage:
25
  """
26
- Генерирует изображение по текстовому описанию.
27
 
28
  Пример:
29
- >>> generate_image("cute kitten on a blanket")
30
- <AgentImage>
31
 
32
  Args:
33
- prompt: Что нарисовать (подробно, на английском лучше).
34
- negative_prompt: Что исключить из изображения.
35
- width: Ширина в пикселях (кратно 8, макс 1024).
36
- height: Высота в пикселях (кратно 8, макс 1024).
37
 
38
  Returns:
39
- AgentImage: Сгенерированное изображение.
40
  """
41
- from huggingface_hub import InferenceClient
42
- from PIL import Image
43
- import io
44
- import os, sys
45
-
46
- print(f"🔍 generate_image: prompt='{prompt[:50]}...', size={width}x{height}", file=sys.stderr)
47
-
48
- client = InferenceClient(token=os.getenv("HF_TOKEN"))
49
-
50
  try:
51
- result = client.text_to_image(
52
- prompt=prompt,
53
- negative_prompt=negative_prompt,
54
- model="black-forest-labs/FLUX.1-schnell",
55
- width=width,
56
- height=height,
57
- num_inference_steps=4,
58
- guidance_scale=3.5
59
- )
60
-
61
- # 1. Получаем PIL объект
62
- if isinstance(result, Image.Image):
63
- image = result
64
- else:
65
- image = Image.open(io.BytesIO(result))
66
-
67
- # 2. 🔑 Форсируем загрузку пикселей в оперативную память!
68
- # Это решает проблему "ленивой загрузки" PIL и предотвращает размер 0x0
69
- image.load()
70
-
71
- print(f"✅ generate_image: изображение {image.size} успешно сгенерировано!", file=sys.stderr)
72
-
73
- # 3. 🔑 Передаем в AgentImage САМ ОБЪЕКТ КАРТИНКИ (не путь к файлу!)
74
- return AgentImage(image)
75
 
 
76
  except Exception as e:
77
- print(f" generate_image exception: {e}", file=sys.stderr)
78
- return f"❌ Ошибка генерации: {str(e)}"
79
 
80
  @tool
81
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -92,8 +56,6 @@ def get_current_time_in_timezone(timezone: str) -> str:
92
  except Exception as e:
93
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
94
 
95
- image_generation_tool = load_tool("m-ric/text-to-image", trust_remote_code=True)
96
-
97
  final_answer = FinalAnswerTool()
98
 
99
  # 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:
@@ -115,7 +77,7 @@ with open("prompts.yaml", 'r') as stream:
115
 
116
  agent = CodeAgent(
117
  model=model,
118
- tools=[final_answer, generate_image], ## add your tools here (don't remove final answer)
119
  max_steps=6,
120
  verbosity_level=1,
121
  grammar=None,
 
16
  from PIL import Image
17
 
18
  @tool
19
+ def get_weather(
20
+ city: str,
21
+ ) -> str:
 
 
 
22
  """
23
+ Отдает прогноз погоды по заданому городу.
24
 
25
  Пример:
26
+ >>> get_weather("какая погода в Токио?")
27
+ <str>
28
 
29
  Args:
30
+ city: название города - str
 
 
 
31
 
32
  Returns:
33
+ str: прогноз погоды.
34
  """
 
 
 
 
 
 
 
 
 
35
  try:
36
+ url = f"https://wttr.in/{location}?format=3"
37
+ response = requests.get(url, timeout=10)
38
+ response.raise_for_status()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ return f"Current weather in {location}: {response.text.strip()}"
41
  except Exception as e:
42
+ return f"Error fetching weather for {location}: {str(e)}"
 
43
 
44
  @tool
45
  def get_current_time_in_timezone(timezone: str) -> str:
 
56
  except Exception as e:
57
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
58
 
 
 
59
  final_answer = FinalAnswerTool()
60
 
61
  # 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:
 
77
 
78
  agent = CodeAgent(
79
  model=model,
80
+ tools=[final_answer, get_weather], ## add your tools here (don't remove final answer)
81
  max_steps=6,
82
  verbosity_level=1,
83
  grammar=None,