jseb4s commited on
Commit
9baa491
·
verified ·
1 Parent(s): 88b2313

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -95
app.py CHANGED
@@ -6,13 +6,21 @@ import yaml
6
  from tools.final_answer import FinalAnswerTool
7
 
8
  from Gradio_UI import GradioUI
 
9
 
 
 
 
 
 
10
  ##############
11
  @tool
12
- def get_game_of_thrones_character_info(character_name: str) -> str:
13
- """A tool that fetches information about a character from Game of Thrones, including their house.
14
  Args:
15
  character_name: The name of the character (e.g., 'Jon Snow').
 
 
16
  """
17
  base_url = "https://anapioficeandfire.com/api/characters"
18
 
@@ -24,7 +32,7 @@ def get_game_of_thrones_character_info(character_name: str) -> str:
24
  characters = response.json()
25
 
26
  if not characters:
27
- return f"No se encontró información para el personaje: {character_name}"
28
 
29
  # Tomar el primer resultado (puede haber varios con el mismo nombre)
30
  character = characters[0]
@@ -48,106 +56,42 @@ def get_game_of_thrones_character_info(character_name: str) -> str:
48
  house_name = house_data.get("name", "Desconocido")
49
  houses.append(house_name)
50
 
51
- # Formatear la respuesta
52
- result = f"Información sobre {name}:\n"
53
- result += f"- Gender: {gender}\n"
54
- result += f"- Culture: {culture}\n"
55
- result += f"- Born: {born}\n"
56
- result += f"- Died: {died}\n"
57
- result += f"- Titles: {titles}\n"
58
- result += f"- Aliases: {aliases}\n"
 
 
 
 
 
 
 
 
 
 
 
59
  if houses:
60
- result += f"- House(s): {', '.join(houses)}\n"
61
  else:
62
- result += "- Casa(s): Ninguna o desconocida\n"
63
 
64
- return result
 
65
 
66
  except Exception as e:
67
- return f"Error al obtener información del personaje: {str(e)}"
68
 
69
 
70
  ###############
71
 
72
 
73
 
74
- @tool
75
- def recommend_books(preferences: str) -> str:
76
- """A tool that recommends books based on a user's preferences, including cover images and purchase links for Colombia.
77
- Args:
78
- preferences: A string describing the user's preferences (e.g., 'Me gustan los libros de ciencia ficción con personajes fuertes').
79
- """
80
- base_url = "https://openlibrary.org/search.json"
81
-
82
- try:
83
- # Convertir las preferencias en una consulta de búsqueda
84
- query = preferences.replace(" ", "+") # Formatear para la URL
85
- params = {"q": query, "fields": "title,author_name,first_publish_year,subject,cover_i,key", "limit": 5}
86
-
87
- # Hacer la solicitud a la API
88
- response = requests.get(base_url, params=params)
89
- response.raise_for_status()
90
- data = response.json()
91
-
92
- # Obtener los libros recomendados
93
- books = data.get("docs", [])
94
-
95
- if not books:
96
- return "No se encontraron libros que coincidan con tus preferencias."
97
-
98
- # Formatear la respuesta
99
- result = "Aquí tienes algunas recomendaciones de libros:\n"
100
- for i, book in enumerate(books, start=1):
101
- title = book.get("title", "Título desconocido")
102
- author = ", ".join(book.get("author_name", ["Autor desconocido"]))
103
- year = book.get("first_publish_year", "Año desconocido")
104
- subjects = ", ".join(book.get("subject", ["Género no especificado"]))[:50] # Limitar la longitud de los géneros
105
- cover_id = book.get("cover_i", "")
106
- book_key = book.get("key", "") # Clave única del libro para obtener más detalles
107
-
108
- # Obtener descripción del libro (si está disponible)
109
- description = "Descripción no disponible."
110
- if book_key:
111
- book_details_url = f"https://openlibrary.org{book_key}.json"
112
- book_details_response = requests.get(book_details_url)
113
- if book_details_response.status_code == 200:
114
- book_details = book_details_response.json()
115
- description = book_details.get("description", "Descripción no disponible.")
116
- if isinstance(description, dict): # Algunas descripciones son diccionarios
117
- description = description.get("value", "Descripción no disponible.")
118
- description = description[:200] + "..." # Limitar la longitud del resumen
119
-
120
- # Generar enlace de portada (si está disponible)
121
- cover_url = f"https://covers.openlibrary.org/b/id/{cover_id}-L.jpg" if cover_id else "Portada no disponible"
122
-
123
- # Generar enlaces de compra para Colombia
124
- search_query = f"{title} {author}".replace(" ", "+")
125
- amazon_link = f"https://www.amazon.com/s?k={search_query}"
126
- mercadolibre_link = f"https://listado.mercadolibre.com.co/{search_query}"
127
-
128
- # Formatear el resumen útil (sin spoilers)
129
- useful_summary = (
130
- f"Este libro es útil porque explora temas como {subjects}. "
131
- f"Es una excelente opción si te gustan los libros que {preferences.lower()}. "
132
- f"Publicado en {year}, ha sido aclamado por su narrativa y personajes memorables."
133
- )
134
-
135
- # Añadir al resultado
136
- result += f"\n{i}. **{title}**\n"
137
- result += f" - Autor: {author}\n"
138
- result += f" - Año de publicación: {year}\n"
139
- result += f" - Géneros: {subjects}...\n"
140
- result += f" - Resumen útil: {useful_summary}\n"
141
- if cover_url != "Portada no disponible":
142
- result += f" - Portada: {cover_url}\n"
143
- result += f" - Comprar en Amazon: {amazon_link}\n"
144
- result += f" - Comprar en MercadoLibre Colombia: {mercadolibre_link}\n"
145
-
146
- return result
147
-
148
- except Exception as e:
149
- return f"Error al buscar recomendaciones de libros: {str(e)}"
150
- ####################
151
 
152
 
153
  final_answer = FinalAnswerTool()
@@ -163,8 +107,7 @@ custom_role_conversions=None,
163
  )
164
 
165
 
166
- # Import tool from Hub
167
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
168
 
169
  with open("prompts.yaml", 'r') as stream:
170
  prompt_templates = yaml.safe_load(stream)
@@ -182,4 +125,31 @@ agent = CodeAgent(
182
  )
183
 
184
 
185
- GradioUI(agent).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from tools.final_answer import FinalAnswerTool
7
 
8
  from Gradio_UI import GradioUI
9
+ import gradio as gr
10
 
11
+
12
+
13
+
14
+ # Import tool from Hub
15
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
16
  ##############
17
  @tool
18
+ def get_game_of_thrones_character_info(character_name: str) -> dict:
19
+ """A tool that fetches information about a character from Game of Thrones, including their house and a generated image.
20
  Args:
21
  character_name: The name of the character (e.g., 'Jon Snow').
22
+ Returns:
23
+ A dictionary with 'text' (character info) and 'image' (generated image URL).
24
  """
25
  base_url = "https://anapioficeandfire.com/api/characters"
26
 
 
32
  characters = response.json()
33
 
34
  if not characters:
35
+ return {"text": f"No se encontró información para el personaje: {character_name}", "image": None}
36
 
37
  # Tomar el primer resultado (puede haber varios con el mismo nombre)
38
  character = characters[0]
 
56
  house_name = house_data.get("name", "Desconocido")
57
  houses.append(house_name)
58
 
59
+ # Generar una descripción para la imagen
60
+ image_prompt = (
61
+ f"Personaje de Juego de Tronos: {name}, "
62
+ f"Género: {gender}, Cultura: {culture}, "
63
+ f"Títulos: {titles}, Alias: {aliases}, "
64
+ f"Casa: {', '.join(houses) if houses else 'Ninguna'}"
65
+ )
66
+
67
+ # Generar la imagen usando la herramienta de generación de imágenes
68
+ image_url = image_generation_tool(image_prompt)
69
+
70
+ # Formatear la respuesta de texto
71
+ text_result = f"Información sobre {name}:\n"
72
+ text_result += f"- Género: {gender}\n"
73
+ text_result += f"- Cultura: {culture}\n"
74
+ text_result += f"- Nacimiento: {born}\n"
75
+ text_result += f"- Muerte: {died}\n"
76
+ text_result += f"- Títulos: {titles}\n"
77
+ text_result += f"- Alias: {aliases}\n"
78
  if houses:
79
+ text_result += f"- Casa(s): {', '.join(houses)}\n"
80
  else:
81
+ text_result += "- Casa(s): Ninguna o desconocida\n"
82
 
83
+ # Devolver el texto y la URL de la imagen
84
+ return {"text": text_result, "image": image_url}
85
 
86
  except Exception as e:
87
+ return {"text": f"Error al obtener información del personaje: {str(e)}", "image": None}
88
 
89
 
90
  ###############
91
 
92
 
93
 
94
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
 
97
  final_answer = FinalAnswerTool()
 
107
  )
108
 
109
 
110
+
 
111
 
112
  with open("prompts.yaml", 'r') as stream:
113
  prompt_templates = yaml.safe_load(stream)
 
125
  )
126
 
127
 
128
+
129
+ ##############
130
+
131
+
132
+ class EnhancedGradioUI(GradioUI):
133
+ def launch(self):
134
+ def run_agent(query):
135
+ response = self.agent.run(query)
136
+ if isinstance(response, dict) and "text" in response and "image" in response:
137
+ return response["text"], response["image"]
138
+ else:
139
+ return response, None
140
+
141
+ # Crear la interfaz de Gradio
142
+ iface = gr.Interface(
143
+ fn=run_agent,
144
+ inputs="text",
145
+ outputs=["text", "image"],
146
+ title="Game of Thrones Character Info",
147
+ description="Obtén información sobre personajes de Juego de Tronos, incluyendo una imagen generada."
148
+ )
149
+ iface.launch()
150
+
151
+ # Lanzar la interfaz mejorada
152
+ EnhancedGradioUI(agent).launch()
153
+
154
+
155
+ #GradioUI(agent).launch()