aleexbescoos commited on
Commit
a024868
·
verified ·
1 Parent(s): 045306d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -36
app.py CHANGED
@@ -1,20 +1,21 @@
1
  # Autors: [Escriu aquí el teu nom] i [nom del company si en teniu]
2
  # Pràctica 26/05/2025 - Agent amb eines noves: traductor i resumidor
3
 
4
- # Instal·lació automàtica de llibreries al principi
5
  import subprocess
6
  import sys
7
 
8
  def install(package):
9
  subprocess.check_call([sys.executable, "-m", "pip", "install", package])
10
 
11
- # Instalar todas las dependencias primero
12
- install("deep-translator")
13
  install("transformers")
 
14
  install("langchain")
15
- install("sentencepiece") # Necesario para algunos modelos de transformers
16
 
17
- # Ahora importar el resto de módulos
18
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
19
  import datetime
20
  import requests
@@ -22,13 +23,17 @@ import pytz
22
  import yaml
23
  from tools.final_answer import FinalAnswerTool
24
  from Gradio_UI import GradioUI
25
- from langchain.tools import Tool # Ahora debería funcionar
26
 
27
- # 🔤 Eina 1: Traducció de text
28
  from deep_translator import GoogleTranslator
29
 
30
  def translate_text(text: str) -> str:
31
- return GoogleTranslator(source='auto', target='en').translate(text)
 
 
 
 
32
 
33
  translate_tool = Tool(
34
  name="TextTranslator",
@@ -36,14 +41,29 @@ translate_tool = Tool(
36
  description="Translate input text to English. Input can be in any language."
37
  )
38
 
39
- # 🧠 Eina 2: Resumidor de text
40
  from transformers import pipeline
41
 
42
- summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
 
 
 
 
 
 
 
 
 
 
43
 
44
  def summarize_text(text: str) -> str:
45
- summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
46
- return summary[0]['summary_text']
 
 
 
 
 
47
 
48
  summarize_tool = Tool(
49
  name="TextSummarizer",
@@ -51,34 +71,20 @@ summarize_tool = Tool(
51
  description="Summarize input text. Use it for long paragraphs or documents."
52
  )
53
 
54
- # Eina 3: Exemple de tool personalitzada
55
- @tool
56
- def my_custom_tool(arg1: str, arg2: int) -> str:
57
- """A tool that does nothing yet
58
- Args:
59
- arg1: the first argument
60
- arg2: the second argument
61
- """
62
- return "What magic will you build?"
63
-
64
- # Eina 4: Consultar l'hora en una zona horària
65
  @tool
66
  def get_current_time_in_timezone(timezone: str) -> str:
67
- """A tool that fetches the current local time in a specified timezone.
68
- Args:
69
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
70
- """
71
  try:
72
  tz = pytz.timezone(timezone)
73
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
74
  return f"The current local time in {timezone} is: {local_time}"
75
  except Exception as e:
76
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
77
 
78
- # Final answer tool (obligatori)
79
  final_answer = FinalAnswerTool()
80
 
81
- # Model LLM
82
  model = HfApiModel(
83
  max_tokens=2096,
84
  temperature=0.5,
@@ -86,20 +92,22 @@ model = HfApiModel(
86
  custom_role_conversions=None,
87
  )
88
 
89
- # Carrega eina de generació d'imatges des de Hugging Face Hub
90
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
 
 
91
 
92
- # Carrega plantilles de prompts
93
  with open("prompts.yaml", 'r') as stream:
94
  prompt_templates = yaml.safe_load(stream)
95
 
96
- # Agent amb totes les eines
97
  agent = CodeAgent(
98
  model=model,
99
  tools=[
100
  translate_tool,
101
  summarize_tool,
102
- my_custom_tool,
103
  get_current_time_in_timezone,
104
  image_generation_tool,
105
  final_answer
@@ -107,5 +115,5 @@ agent = CodeAgent(
107
  prompt_templates=prompt_templates
108
  )
109
 
110
- # Llançar la interfície
111
  GradioUI(agent).launch()
 
1
  # Autors: [Escriu aquí el teu nom] i [nom del company si en teniu]
2
  # Pràctica 26/05/2025 - Agent amb eines noves: traductor i resumidor
3
 
4
+ # 1. Instal·lació automàtica de llibreries (al principi del fitxer)
5
  import subprocess
6
  import sys
7
 
8
  def install(package):
9
  subprocess.check_call([sys.executable, "-m", "pip", "install", package])
10
 
11
+ # Instalar primero las dependencias pesadas
12
+ install("torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu")
13
  install("transformers")
14
+ install("deep-translator")
15
  install("langchain")
16
+ install("sentencepiece")
17
 
18
+ # 2. Importaciones después de las instalaciones
19
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
20
  import datetime
21
  import requests
 
23
  import yaml
24
  from tools.final_answer import FinalAnswerTool
25
  from Gradio_UI import GradioUI
26
+ from langchain.tools import Tool
27
 
28
+ # 3. Configuración del traductor (no requiere PyTorch/TensorFlow)
29
  from deep_translator import GoogleTranslator
30
 
31
  def translate_text(text: str) -> str:
32
+ """Traduce texto a inglés usando Google Translate"""
33
+ try:
34
+ return GoogleTranslator(source='auto', target='en').translate(text)
35
+ except Exception as e:
36
+ return f"Error en traducción: {str(e)}"
37
 
38
  translate_tool = Tool(
39
  name="TextTranslator",
 
41
  description="Translate input text to English. Input can be in any language."
42
  )
43
 
44
+ # 4. Configuración alternativa del resumidor (sin PyTorch/TensorFlow)
45
  from transformers import pipeline
46
 
47
+ try:
48
+ # Intentamos cargar un modelo pequeño que pueda funcionar sin GPU
49
+ summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
50
+ except:
51
+ # Fallback a una implementación más simple si falla
52
+ def simple_summarizer(text: str) -> str:
53
+ """Resumen básico tomando las primeras oraciones"""
54
+ sentences = text.split('.')
55
+ return '. '.join(sentences[:3]) + '.' if len(sentences) > 3 else text
56
+
57
+ summarizer = simple_summarizer
58
 
59
  def summarize_text(text: str) -> str:
60
+ try:
61
+ if callable(summarizer):
62
+ summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
63
+ return summary[0]['summary_text'] if isinstance(summary, list) else summary
64
+ return summarizer(text)
65
+ except Exception as e:
66
+ return f"Error en resumen: {str(e)}"
67
 
68
  summarize_tool = Tool(
69
  name="TextSummarizer",
 
71
  description="Summarize input text. Use it for long paragraphs or documents."
72
  )
73
 
74
+ # 5. Herramientas adicionales
 
 
 
 
 
 
 
 
 
 
75
  @tool
76
  def get_current_time_in_timezone(timezone: str) -> str:
77
+ """Obtiene la hora actual en una zona horaria específica"""
 
 
 
78
  try:
79
  tz = pytz.timezone(timezone)
80
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
81
  return f"The current local time in {timezone} is: {local_time}"
82
  except Exception as e:
83
+ return f"Error fetching time: {str(e)}"
84
 
85
+ # 6. Configuración del agente
86
  final_answer = FinalAnswerTool()
87
 
 
88
  model = HfApiModel(
89
  max_tokens=2096,
90
  temperature=0.5,
 
92
  custom_role_conversions=None,
93
  )
94
 
95
+ try:
96
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
97
+ except:
98
+ @tool
99
+ def image_generation_tool(prompt: str) -> str:
100
+ return "Image generation disabled in this environment"
101
 
102
+ # 7. Carga de plantillas y creación del agente
103
  with open("prompts.yaml", 'r') as stream:
104
  prompt_templates = yaml.safe_load(stream)
105
 
 
106
  agent = CodeAgent(
107
  model=model,
108
  tools=[
109
  translate_tool,
110
  summarize_tool,
 
111
  get_current_time_in_timezone,
112
  image_generation_tool,
113
  final_answer
 
115
  prompt_templates=prompt_templates
116
  )
117
 
118
+ # 8. Iniciar la interfaz
119
  GradioUI(agent).launch()