Spaces:
Running
on
Zero
Running
on
Zero
Delete app.py
Browse files
app.py
DELETED
@@ -1,264 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import requests
|
3 |
-
import gradio as gr
|
4 |
-
from download_url import download_text_and_title
|
5 |
-
from cache_system import CacheHandler
|
6 |
-
from collections import OrderedDict
|
7 |
-
from typing import Any, Iterable, List
|
8 |
-
import datetime
|
9 |
-
import json
|
10 |
-
|
11 |
-
server = os.environ.get("SERVER") or "http://localhost:7861/generate"
|
12 |
-
auth_token = os.environ.get("TOKEN") or True
|
13 |
-
API_KEY = os.environ.get("API_KEY") or None
|
14 |
-
|
15 |
-
|
16 |
-
total_runs = 0
|
17 |
-
|
18 |
-
|
19 |
-
def call_vllm_server(tittle, body, mode, stream=True):
|
20 |
-
api_url = server
|
21 |
-
headers = {"User-Agent": "Test Client"}
|
22 |
-
|
23 |
-
json = {
|
24 |
-
"n": 1,
|
25 |
-
"tittle": tittle,
|
26 |
-
"body": body,
|
27 |
-
"mode": mode,
|
28 |
-
"max_tokens": 4096,
|
29 |
-
"temperature": 0.15,
|
30 |
-
"top_p": 0.1,
|
31 |
-
"top_k": 40,
|
32 |
-
"repetition_penalty": 1.1,
|
33 |
-
"stop": [
|
34 |
-
"<s>",
|
35 |
-
"</s>",
|
36 |
-
"\\n",
|
37 |
-
"<|im_end|>",
|
38 |
-
],
|
39 |
-
"stream": stream,
|
40 |
-
"api_key": API_KEY,
|
41 |
-
}
|
42 |
-
response = requests.post(api_url, headers=headers, json=json)
|
43 |
-
return response
|
44 |
-
|
45 |
-
|
46 |
-
def get_streaming_response(response: requests.Response) -> Iterable[List[str]]:
|
47 |
-
for chunk in response.iter_lines(
|
48 |
-
chunk_size=8192, decode_unicode=False, delimiter=b"\0"
|
49 |
-
):
|
50 |
-
if chunk:
|
51 |
-
data = json.loads(chunk.decode("utf-8"))
|
52 |
-
output = data["text"]
|
53 |
-
yield output
|
54 |
-
|
55 |
-
|
56 |
-
class HuggingFaceDatasetSaver_custom(gr.HuggingFaceDatasetSaver):
|
57 |
-
def _deserialize_components(
|
58 |
-
self,
|
59 |
-
data_dir,
|
60 |
-
flag_data: list[Any],
|
61 |
-
flag_option: str = "",
|
62 |
-
username: str = "",
|
63 |
-
) -> tuple[dict[Any, Any], list[Any]]:
|
64 |
-
"""Deserialize components and return the corresponding row for the flagged sample.
|
65 |
-
|
66 |
-
Images/audio are saved to disk as individual files.
|
67 |
-
"""
|
68 |
-
# Components that can have a preview on dataset repos
|
69 |
-
file_preview_types = {gr.Audio: "Audio", gr.Image: "Image"}
|
70 |
-
|
71 |
-
# Generate the row corresponding to the flagged sample
|
72 |
-
features = OrderedDict()
|
73 |
-
row = []
|
74 |
-
for component, sample in zip(self.components, flag_data):
|
75 |
-
label = component.label or ""
|
76 |
-
features[label] = {"dtype": "string", "_type": "Value"}
|
77 |
-
row.append(sample)
|
78 |
-
|
79 |
-
features["flag"] = {"dtype": "string", "_type": "Value"}
|
80 |
-
features["username"] = {"dtype": "string", "_type": "Value"}
|
81 |
-
row.append(flag_option)
|
82 |
-
row.append(username)
|
83 |
-
return features, row
|
84 |
-
|
85 |
-
|
86 |
-
def finish_generation(text: str) -> str:
|
87 |
-
return f"{text}\n\n⬇️ Ayuda a mejorar la herramienta marcando si el resumen es correcto o no.⬇️"
|
88 |
-
|
89 |
-
|
90 |
-
def generate_text(
|
91 |
-
url: str, mode: int, progress=gr.Progress(track_tqdm=False)
|
92 |
-
) -> (str, str):
|
93 |
-
global cache_handler
|
94 |
-
global total_runs
|
95 |
-
|
96 |
-
total_runs += 1
|
97 |
-
print(f"Total runs: {total_runs}. Last run: {datetime.datetime.now()}")
|
98 |
-
|
99 |
-
url = url.strip()
|
100 |
-
|
101 |
-
if url.startswith("https://twitter.com/") or url.startswith("https://x.com/"):
|
102 |
-
yield (
|
103 |
-
"🤖 Vaya, parece que has introducido la url de un tweet. No puedo acceder a tweets, tienes que introducir la URL de una noticia.",
|
104 |
-
"❌❌❌ Si el tweet contiene una noticia, dame la URL de la noticia ❌❌❌",
|
105 |
-
"Error",
|
106 |
-
)
|
107 |
-
return (
|
108 |
-
"🤖 Vaya, parece que has introducido la url de un tweet. No puedo acceder a tweets, tienes que introducir la URL de una noticia.",
|
109 |
-
"❌❌❌ Si el tweet contiene una noticia, dame la URL de la noticia ❌❌❌",
|
110 |
-
"Error",
|
111 |
-
)
|
112 |
-
|
113 |
-
# 1) Download the article
|
114 |
-
|
115 |
-
progress(0, desc="🤖 Accediendo a la noticia")
|
116 |
-
|
117 |
-
# First, check if the URL is in the cache
|
118 |
-
title, text, temp = cache_handler.get_from_cache(url, mode)
|
119 |
-
if title is not None and text is not None and temp is not None:
|
120 |
-
temp = finish_generation(temp)
|
121 |
-
yield title, temp, text
|
122 |
-
return title, temp, text
|
123 |
-
else:
|
124 |
-
try:
|
125 |
-
title, text, url = download_text_and_title(url)
|
126 |
-
except Exception as e:
|
127 |
-
print(e)
|
128 |
-
title = None
|
129 |
-
text = None
|
130 |
-
|
131 |
-
if title is None or text is None:
|
132 |
-
yield (
|
133 |
-
"🤖 No he podido acceder a la notica, asegurate que la URL es correcta y que es posible acceder a la noticia desde un navegador.",
|
134 |
-
"❌❌❌ Inténtalo de nuevo ❌❌❌",
|
135 |
-
"Error",
|
136 |
-
)
|
137 |
-
return (
|
138 |
-
"🤖 No he podido acceder a la notica, asegurate que la URL es correcta y que es posible acceder a la noticia desde un navegador.",
|
139 |
-
"❌❌❌ Inténtalo de nuevo ❌❌❌",
|
140 |
-
"Error",
|
141 |
-
)
|
142 |
-
|
143 |
-
# Test if the redirected and clean url is in the cache
|
144 |
-
_, _, temp = cache_handler.get_from_cache(url, mode, second_try=True)
|
145 |
-
if temp is not None:
|
146 |
-
temp = finish_generation(temp)
|
147 |
-
yield title, temp, text
|
148 |
-
return title, temp, text
|
149 |
-
|
150 |
-
progress(0.5, desc="🤖 Leyendo noticia")
|
151 |
-
|
152 |
-
try:
|
153 |
-
response = call_vllm_server(title, text, mode, stream=True)
|
154 |
-
for h in get_streaming_response(response):
|
155 |
-
temp = h[0]
|
156 |
-
yield title, temp, text
|
157 |
-
|
158 |
-
except Exception as e:
|
159 |
-
print(e)
|
160 |
-
yield (
|
161 |
-
"🤖 El servidor no se encuentra disponible.",
|
162 |
-
"❌❌❌ Inténtalo de nuevo más tarde ❌❌❌",
|
163 |
-
"Error",
|
164 |
-
)
|
165 |
-
return (
|
166 |
-
"🤖 El servidor no se encuentra disponible.",
|
167 |
-
"❌❌❌ Inténtalo de nuevo más tarde ❌❌❌",
|
168 |
-
"Error",
|
169 |
-
)
|
170 |
-
|
171 |
-
cache_handler.add_to_cache(
|
172 |
-
url=url, title=title, text=text, summary_type=mode, summary=temp
|
173 |
-
)
|
174 |
-
temp = finish_generation(temp)
|
175 |
-
yield title, temp, text
|
176 |
-
|
177 |
-
hits, misses, cache_len = cache_handler.get_cache_stats()
|
178 |
-
print(
|
179 |
-
f"Hits: {hits}, misses: {misses}, cache length: {cache_len}. Percent hits: {round(hits/(hits+misses)*100,2)}%."
|
180 |
-
)
|
181 |
-
return title, temp, text
|
182 |
-
|
183 |
-
|
184 |
-
cache_handler = CacheHandler(max_cache_size=1000)
|
185 |
-
hf_writer = HuggingFaceDatasetSaver_custom(
|
186 |
-
auth_token, "Iker/Clickbait-News", private=True, separate_dirs=False
|
187 |
-
)
|
188 |
-
|
189 |
-
|
190 |
-
demo = gr.Interface(
|
191 |
-
generate_text,
|
192 |
-
inputs=[
|
193 |
-
gr.Textbox(
|
194 |
-
label="🌐 URL de la noticia",
|
195 |
-
info="Introduce la URL de la noticia que deseas resumir.",
|
196 |
-
value="https://ikergarcia1996.github.io/Iker-Garcia-Ferrero/",
|
197 |
-
interactive=True,
|
198 |
-
),
|
199 |
-
gr.Slider(
|
200 |
-
minimum=0,
|
201 |
-
maximum=100,
|
202 |
-
step=50,
|
203 |
-
value=50,
|
204 |
-
label="🎚️ Nivel de resumen",
|
205 |
-
info="""¿Hasta qué punto quieres resumir la noticia?
|
206 |
-
|
207 |
-
Si solo deseas un resumen, selecciona 0.
|
208 |
-
|
209 |
-
Si buscas un resumen y desmontar el clickbait, elige 50.
|
210 |
-
|
211 |
-
Para obtener solo la respuesta al clickbait, selecciona 100""",
|
212 |
-
interactive=True,
|
213 |
-
),
|
214 |
-
],
|
215 |
-
outputs=[
|
216 |
-
gr.Textbox(
|
217 |
-
label="📰 Titular de la noticia",
|
218 |
-
interactive=False,
|
219 |
-
placeholder="Aquí aparecerá el título de la noticia",
|
220 |
-
),
|
221 |
-
gr.Textbox(
|
222 |
-
label="🗒️ Resumen",
|
223 |
-
interactive=False,
|
224 |
-
placeholder="Aquí aparecerá el resumen de la noticia.",
|
225 |
-
),
|
226 |
-
gr.Textbox(
|
227 |
-
label="Noticia completa",
|
228 |
-
visible=False,
|
229 |
-
render=False,
|
230 |
-
interactive=False,
|
231 |
-
placeholder="Aquí aparecerá el resumen de la noticia.",
|
232 |
-
),
|
233 |
-
],
|
234 |
-
# title="⚔️ Clickbait Fighter! ⚔️",
|
235 |
-
thumbnail="https://huggingface.co/spaces/Iker/ClickbaitFighter/resolve/main/logo2.png",
|
236 |
-
theme="JohnSmith9982/small_and_pretty",
|
237 |
-
description="""
|
238 |
-
<table>
|
239 |
-
<tr>
|
240 |
-
<td style="width:100%"><img src="https://huggingface.co/spaces/Iker/ClickbaitFighter/resolve/main/head.png" align="right" width="100%"> </td>
|
241 |
-
</tr>
|
242 |
-
</table>
|
243 |
-
|
244 |
-
<p align="center"> <a href="https://www.omegaai.io/"> <img src="https://huggingface.co/spaces/Iker/ClickbaitFighter/resolve/main/omegaai.png" align="center" width="15%"> </a> <a href="https://0dai.omegaai.io/"> <img src="https://huggingface.co/spaces/Iker/ClickbaitFighter/resolve/main/0dai.png" align="center" width="15%"> </a></p>
|
245 |
-
|
246 |
-
<p align="justify">Esta Inteligencia Artificial es capaz de generar un resumen de una sola frase que revela la verdad detrás de un titular sensacionalista o clickbait. Solo tienes que introducir la URL de la noticia. La IA accederá a la noticia, la leerá y en cuestión de segundos generará un resumen de una sola frase que revele la verdad detrás del titular.</p>
|
247 |
-
|
248 |
-
🎚 Ajusta el nivel de resumen con el control deslizante. Cuanto maś alto, más corto será el resumen.
|
249 |
-
|
250 |
-
⌚ La IA se encuentra corriendo en un hardware bastante modesto, debería tardar menos de 30 segundos en generar el resumen, pero si muchos usuarios usan la app a la vez, tendrás que esperar tu turno.
|
251 |
-
|
252 |
-
💸 Este es un projecto sin ánimo de lucro, no se genera ningún tipo de ingreso con esta app. Los datos, la IA y el código se publicarán para su uso en la investigación académica. No puedes usar esta app para ningún uso comercial.
|
253 |
-
|
254 |
-
🧪 El modelo se encuentra en fase de desarrollo, si quieres ayudar a mejorarlo puedes usar los botones 👍 y 👎 para valorar el resumen. ¡Gracias por tu ayuda!""",
|
255 |
-
article="Esta Inteligencia Artificial ha sido generada por Iker García-Ferrero. Puedes saber más sobre mi trabajo en mi [página web](https://ikergarcia1996.github.io/Iker-Garcia-Ferrero/) o mi perfil de [X](https://twitter.com/iker_garciaf). Puedes ponerte en contacto conmigo a través de correo electrónico (ver web) y X.",
|
256 |
-
cache_examples=False,
|
257 |
-
allow_flagging="manual",
|
258 |
-
flagging_options=[("👍", "correct"), ("👎", "incorrect")],
|
259 |
-
flagging_callback=hf_writer,
|
260 |
-
concurrency_limit=20,
|
261 |
-
)
|
262 |
-
|
263 |
-
demo.queue(max_size=None)
|
264 |
-
demo.launch(share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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