Spaces:
Runtime error
Runtime error
CamiloVega
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -12,25 +12,25 @@ from typing import Optional, Dict, Any
|
|
12 |
import fitz # PyMuPDF
|
13 |
import os
|
14 |
|
15 |
-
#
|
16 |
logging.basicConfig(
|
17 |
level=logging.INFO,
|
18 |
format='%(asctime)s - %(levelname)s - %(message)s'
|
19 |
)
|
20 |
logger = logging.getLogger(__name__)
|
21 |
|
22 |
-
#
|
23 |
HUGGINGFACE_TOKEN = os.getenv('HUGGINGFACE_TOKEN')
|
24 |
if not HUGGINGFACE_TOKEN:
|
25 |
-
logger.warning("HUGGINGFACE_TOKEN
|
26 |
-
raise ValueError("HUGGINGFACE_TOKEN
|
27 |
|
28 |
-
# Hugging Face
|
29 |
login(token=HUGGINGFACE_TOKEN)
|
30 |
|
31 |
class NewsGenerator:
|
32 |
def __init__(self):
|
33 |
-
self.device = "
|
34 |
self.whisper_model = None
|
35 |
self.llm_model = None
|
36 |
self.tokenizer = None
|
@@ -38,10 +38,10 @@ class NewsGenerator:
|
|
38 |
self._load_models()
|
39 |
|
40 |
def _load_models(self):
|
41 |
-
"""
|
42 |
try:
|
43 |
-
#
|
44 |
-
model_name = "
|
45 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
46 |
model_name,
|
47 |
use_fast=True,
|
@@ -50,37 +50,43 @@ class NewsGenerator:
|
|
50 |
|
51 |
self.llm_model = AutoModelForCausalLM.from_pretrained(
|
52 |
model_name,
|
53 |
-
device_map="
|
54 |
-
torch_dtype=torch.
|
55 |
-
load_in_4bit=True,
|
56 |
low_cpu_mem_usage=True,
|
57 |
token=HUGGINGFACE_TOKEN
|
58 |
)
|
59 |
|
60 |
-
# Whisper
|
61 |
self.whisper_model = whisper.load_model(
|
62 |
-
"
|
63 |
-
device=
|
64 |
)
|
65 |
|
66 |
except Exception as e:
|
67 |
-
logger.error(f"Error
|
68 |
raise
|
69 |
|
70 |
def transcribe_audio(self, audio_path: str) -> str:
|
71 |
-
"""
|
72 |
try:
|
73 |
result = self.whisper_model.transcribe(audio_path)
|
74 |
return result.get("text", "")
|
75 |
except Exception as e:
|
76 |
-
logger.error(f"
|
77 |
return ""
|
78 |
|
79 |
def generate_news(self, prompt: str, max_length: int = 512) -> str:
|
80 |
-
"""
|
81 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
inputs = self.tokenizer(
|
83 |
-
|
84 |
return_tensors="pt"
|
85 |
).to(self.device)
|
86 |
|
@@ -96,11 +102,11 @@ class NewsGenerator:
|
|
96 |
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
97 |
|
98 |
except Exception as e:
|
99 |
-
logger.error(f"
|
100 |
-
return "
|
101 |
|
102 |
def read_document(file_path: str) -> str:
|
103 |
-
"""
|
104 |
try:
|
105 |
if file_path.endswith(".pdf"):
|
106 |
with fitz.open(file_path) as doc:
|
@@ -116,99 +122,98 @@ def read_document(file_path: str) -> str:
|
|
116 |
return pd.read_csv(file_path).to_string()
|
117 |
return ""
|
118 |
except Exception as e:
|
119 |
-
logger.error(f"
|
120 |
return ""
|
121 |
|
122 |
def read_url(url: str) -> str:
|
123 |
-
"""
|
124 |
try:
|
125 |
response = requests.get(url, timeout=15)
|
126 |
response.raise_for_status()
|
127 |
return BeautifulSoup(response.content, 'html.parser').get_text(separator=' ', strip=True)
|
128 |
except Exception as e:
|
129 |
-
logger.error(f"
|
130 |
return ""
|
131 |
|
132 |
def process_social_media(url: str) -> Dict[str, Any]:
|
133 |
-
"""
|
134 |
try:
|
135 |
text = read_url(url)
|
136 |
return {"text": text, "video": None}
|
137 |
except Exception as e:
|
138 |
-
logger.error(f"
|
139 |
return {"text": "", "video": None}
|
140 |
|
141 |
def create_interface():
|
142 |
-
"""
|
143 |
generator = NewsGenerator()
|
144 |
|
145 |
-
with gr.Blocks(title="
|
146 |
gr.Markdown("""
|
147 |
-
# 📰
|
148 |
|
149 |
-
|
150 |
-
multiple sources including text, documents, audio, and web content to generate comprehensive news stories.
|
151 |
|
152 |
-
###
|
153 |
-
-
|
154 |
-
-
|
155 |
-
-
|
156 |
-
-
|
157 |
|
158 |
---
|
159 |
-
|
160 |
-
[LinkedIn
|
161 |
""")
|
162 |
|
163 |
with gr.Row():
|
164 |
with gr.Column(scale=3):
|
165 |
main_input = gr.Textbox(
|
166 |
-
label="
|
167 |
-
placeholder="
|
168 |
lines=3
|
169 |
)
|
170 |
additional_data = gr.Textbox(
|
171 |
-
label="
|
172 |
-
placeholder="
|
173 |
lines=3
|
174 |
)
|
175 |
|
176 |
-
with gr.Accordion("
|
177 |
doc_upload = gr.File(
|
178 |
-
label="
|
179 |
file_types=[".pdf", ".docx", ".xlsx", ".csv"]
|
180 |
)
|
181 |
audio_upload = gr.File(
|
182 |
-
label="
|
183 |
file_types=["audio", "video"]
|
184 |
)
|
185 |
url_input = gr.Textbox(
|
186 |
-
label="
|
187 |
placeholder="https://..."
|
188 |
)
|
189 |
social_input = gr.Textbox(
|
190 |
-
label="
|
191 |
placeholder="https://..."
|
192 |
)
|
193 |
|
194 |
length_slider = gr.Slider(
|
195 |
100, 1000, value=400,
|
196 |
-
label="
|
197 |
)
|
198 |
tone_select = gr.Dropdown(
|
199 |
-
label="
|
200 |
-
choices=["Formal", "Neutral", "
|
201 |
value="Neutral"
|
202 |
)
|
203 |
|
204 |
with gr.Column(scale=2):
|
205 |
output_news = gr.Textbox(
|
206 |
-
label="
|
207 |
lines=18,
|
208 |
interactive=False
|
209 |
)
|
210 |
-
generate_btn = gr.Button("
|
211 |
-
status = gr.Textbox(label="
|
212 |
|
213 |
def process_and_generate(
|
214 |
main_input: str,
|
@@ -221,37 +226,37 @@ def create_interface():
|
|
221 |
tone: str
|
222 |
):
|
223 |
try:
|
224 |
-
#
|
225 |
doc_content = read_document(document) if document else ""
|
226 |
audio_content = generator.transcribe_audio(audio) if audio else ""
|
227 |
url_content = read_url(url) if url else ""
|
228 |
social_content = process_social_media(social_url) if social_url else {"text": ""}
|
229 |
|
230 |
-
#
|
231 |
prompt = f"""
|
232 |
-
##
|
233 |
-
-
|
234 |
-
-
|
235 |
-
-
|
236 |
|
237 |
-
##
|
238 |
-
-
|
239 |
-
- Audio: {audio_content[:
|
240 |
-
- URL: {url_content[:
|
241 |
-
- Social
|
242 |
|
243 |
-
##
|
244 |
-
-
|
245 |
-
-
|
246 |
-
-
|
247 |
-
-
|
248 |
"""
|
249 |
|
250 |
-
return generator.generate_news(prompt, length), "✅
|
251 |
|
252 |
except Exception as e:
|
253 |
logger.error(str(e))
|
254 |
-
return f"Error: {str(e)}", "❌
|
255 |
|
256 |
generate_btn.click(
|
257 |
fn=process_and_generate,
|
|
|
12 |
import fitz # PyMuPDF
|
13 |
import os
|
14 |
|
15 |
+
# Configuración de logging
|
16 |
logging.basicConfig(
|
17 |
level=logging.INFO,
|
18 |
format='%(asctime)s - %(levelname)s - %(message)s'
|
19 |
)
|
20 |
logger = logging.getLogger(__name__)
|
21 |
|
22 |
+
# Obtener token de Hugging Face
|
23 |
HUGGINGFACE_TOKEN = os.getenv('HUGGINGFACE_TOKEN')
|
24 |
if not HUGGINGFACE_TOKEN:
|
25 |
+
logger.warning("HUGGINGFACE_TOKEN no encontrado en variables de entorno")
|
26 |
+
raise ValueError("Configura HUGGINGFACE_TOKEN en las variables de entorno")
|
27 |
|
28 |
+
# Autenticación en Hugging Face
|
29 |
login(token=HUGGINGFACE_TOKEN)
|
30 |
|
31 |
class NewsGenerator:
|
32 |
def __init__(self):
|
33 |
+
self.device = "cpu" # Forzar uso de CPU
|
34 |
self.whisper_model = None
|
35 |
self.llm_model = None
|
36 |
self.tokenizer = None
|
|
|
38 |
self._load_models()
|
39 |
|
40 |
def _load_models(self):
|
41 |
+
"""Carga optimizada de modelos para CPU"""
|
42 |
try:
|
43 |
+
# Modelo DeepSeek ligero
|
44 |
+
model_name = "deepseek-ai/deepseek-r1-distill-queen-1.5b"
|
45 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
46 |
model_name,
|
47 |
use_fast=True,
|
|
|
50 |
|
51 |
self.llm_model = AutoModelForCausalLM.from_pretrained(
|
52 |
model_name,
|
53 |
+
device_map="cpu",
|
54 |
+
torch_dtype=torch.float32, # Usar float32 para CPU
|
|
|
55 |
low_cpu_mem_usage=True,
|
56 |
token=HUGGINGFACE_TOKEN
|
57 |
)
|
58 |
|
59 |
+
# Configuración de Whisper (versión reducida)
|
60 |
self.whisper_model = whisper.load_model(
|
61 |
+
"tiny.en",
|
62 |
+
device="cpu"
|
63 |
)
|
64 |
|
65 |
except Exception as e:
|
66 |
+
logger.error(f"Error cargando modelos: {str(e)}")
|
67 |
raise
|
68 |
|
69 |
def transcribe_audio(self, audio_path: str) -> str:
|
70 |
+
"""Transcripción de audio con manejo de errores"""
|
71 |
try:
|
72 |
result = self.whisper_model.transcribe(audio_path)
|
73 |
return result.get("text", "")
|
74 |
except Exception as e:
|
75 |
+
logger.error(f"Error en transcripción: {str(e)}")
|
76 |
return ""
|
77 |
|
78 |
def generate_news(self, prompt: str, max_length: int = 512) -> str:
|
79 |
+
"""Generación de noticias con DeepSeek"""
|
80 |
try:
|
81 |
+
# Formato de prompt específico para DeepSeek
|
82 |
+
formatted_prompt = (
|
83 |
+
f"<|System|>\nEres un periodista profesional. Genera un artículo noticioso "
|
84 |
+
f"basado en estos datos:\n{prompt}\n<|End|>\n"
|
85 |
+
f"<|User|>\nRedacta el artículo:<|End|>\n<|Assistant|>"
|
86 |
+
)
|
87 |
+
|
88 |
inputs = self.tokenizer(
|
89 |
+
formatted_prompt,
|
90 |
return_tensors="pt"
|
91 |
).to(self.device)
|
92 |
|
|
|
102 |
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
103 |
|
104 |
except Exception as e:
|
105 |
+
logger.error(f"Error en generación: {str(e)}")
|
106 |
+
return "Error generando el artículo"
|
107 |
|
108 |
def read_document(file_path: str) -> str:
|
109 |
+
"""Lectura optimizada de documentos"""
|
110 |
try:
|
111 |
if file_path.endswith(".pdf"):
|
112 |
with fitz.open(file_path) as doc:
|
|
|
122 |
return pd.read_csv(file_path).to_string()
|
123 |
return ""
|
124 |
except Exception as e:
|
125 |
+
logger.error(f"Error leyendo documento: {str(e)}")
|
126 |
return ""
|
127 |
|
128 |
def read_url(url: str) -> str:
|
129 |
+
"""Extracción de contenido web"""
|
130 |
try:
|
131 |
response = requests.get(url, timeout=15)
|
132 |
response.raise_for_status()
|
133 |
return BeautifulSoup(response.content, 'html.parser').get_text(separator=' ', strip=True)
|
134 |
except Exception as e:
|
135 |
+
logger.error(f"Error leyendo URL: {str(e)}")
|
136 |
return ""
|
137 |
|
138 |
def process_social_media(url: str) -> Dict[str, Any]:
|
139 |
+
"""Procesamiento de redes sociales"""
|
140 |
try:
|
141 |
text = read_url(url)
|
142 |
return {"text": text, "video": None}
|
143 |
except Exception as e:
|
144 |
+
logger.error(f"Error procesando red social: {str(e)}")
|
145 |
return {"text": "", "video": None}
|
146 |
|
147 |
def create_interface():
|
148 |
+
"""Interfaz de usuario de Gradio"""
|
149 |
generator = NewsGenerator()
|
150 |
|
151 |
+
with gr.Blocks(title="Generador de Noticias AI", theme=gr.themes.Soft()) as app:
|
152 |
gr.Markdown("""
|
153 |
+
# 📰 Generador de Noticias AI
|
154 |
|
155 |
+
Transforma datos en bruto en artículos periodísticos profesionales usando IA avanzada.
|
|
|
156 |
|
157 |
+
### Características:
|
158 |
+
- Procesamiento multi-fuente (texto, documentos, audio, web)
|
159 |
+
- Estilos periodísticos profesionales
|
160 |
+
- Transcripción automática de audio
|
161 |
+
- Longitud y tono personalizables
|
162 |
|
163 |
---
|
164 |
+
Desarrollado por Camilo Vega, Consultor en IA
|
165 |
+
[Perfil de LinkedIn](https://www.linkedin.com/in/camilo-vega-169084b1/)
|
166 |
""")
|
167 |
|
168 |
with gr.Row():
|
169 |
with gr.Column(scale=3):
|
170 |
main_input = gr.Textbox(
|
171 |
+
label="Tema Principal",
|
172 |
+
placeholder="Ingrese el tema principal o instrucciones...",
|
173 |
lines=3
|
174 |
)
|
175 |
additional_data = gr.Textbox(
|
176 |
+
label="Datos Adicionales",
|
177 |
+
placeholder="Hechos clave, nombres, fechas...",
|
178 |
lines=3
|
179 |
)
|
180 |
|
181 |
+
with gr.Accordion("Fuentes Adicionales", open=False):
|
182 |
doc_upload = gr.File(
|
183 |
+
label="Subir Documento",
|
184 |
file_types=[".pdf", ".docx", ".xlsx", ".csv"]
|
185 |
)
|
186 |
audio_upload = gr.File(
|
187 |
+
label="Subir Audio/Video",
|
188 |
file_types=["audio", "video"]
|
189 |
)
|
190 |
url_input = gr.Textbox(
|
191 |
+
label="URL de Referencia",
|
192 |
placeholder="https://..."
|
193 |
)
|
194 |
social_input = gr.Textbox(
|
195 |
+
label="URL de Red Social",
|
196 |
placeholder="https://..."
|
197 |
)
|
198 |
|
199 |
length_slider = gr.Slider(
|
200 |
100, 1000, value=400,
|
201 |
+
label="Longitud del Artículo (palabras)"
|
202 |
)
|
203 |
tone_select = gr.Dropdown(
|
204 |
+
label="Tono Periodístico",
|
205 |
+
choices=["Formal", "Neutral", "Investigativo", "Narrativo"],
|
206 |
value="Neutral"
|
207 |
)
|
208 |
|
209 |
with gr.Column(scale=2):
|
210 |
output_news = gr.Textbox(
|
211 |
+
label="Artículo Generado",
|
212 |
lines=18,
|
213 |
interactive=False
|
214 |
)
|
215 |
+
generate_btn = gr.Button("Generar Artículo", variant="primary")
|
216 |
+
status = gr.Textbox(label="Estado", interactive=False)
|
217 |
|
218 |
def process_and_generate(
|
219 |
main_input: str,
|
|
|
226 |
tone: str
|
227 |
):
|
228 |
try:
|
229 |
+
# Procesar fuentes adicionales
|
230 |
doc_content = read_document(document) if document else ""
|
231 |
audio_content = generator.transcribe_audio(audio) if audio else ""
|
232 |
url_content = read_url(url) if url else ""
|
233 |
social_content = process_social_media(social_url) if social_url else {"text": ""}
|
234 |
|
235 |
+
# Construir prompt estructurado
|
236 |
prompt = f"""
|
237 |
+
## Instrucciones:
|
238 |
+
- Tema Principal: {main_input}
|
239 |
+
- Datos Proporcionados: {additional_data}
|
240 |
+
- Tono Requerido: {tone}
|
241 |
|
242 |
+
## Fuentes:
|
243 |
+
- Documento: {doc_content[:500]}...
|
244 |
+
- Audio: {audio_content[:300]}...
|
245 |
+
- URL: {url_content[:500]}...
|
246 |
+
- Red Social: {social_content['text'][:300]}...
|
247 |
|
248 |
+
## Requisitos:
|
249 |
+
- Estructura profesional (titular, lead, cuerpo)
|
250 |
+
- Incluir las 5W
|
251 |
+
- Citas relevantes si aplica
|
252 |
+
- Longitud: {length} palabras
|
253 |
"""
|
254 |
|
255 |
+
return generator.generate_news(prompt, length), "✅ Generación exitosa"
|
256 |
|
257 |
except Exception as e:
|
258 |
logger.error(str(e))
|
259 |
+
return f"Error: {str(e)}", "❌ Error en generación"
|
260 |
|
261 |
generate_btn.click(
|
262 |
fn=process_and_generate,
|