Iker commited on
Commit
7a94167
·
verified ·
1 Parent(s): eb10d48

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -20
app.py CHANGED
@@ -1,22 +1,62 @@
1
  import os
2
-
3
  import gradio as gr
4
  from download_url import download_text_and_title
5
  from cache_system import CacheHandler
6
- from gradio_client import Client
7
  from collections import OrderedDict
8
- from typing import Any
9
  import datetime
 
10
 
11
-
12
- server = os.environ.get("SERVER") or True
13
  auth_token = os.environ.get("TOKEN") or True
 
14
 
15
- client = Client(server, hf_token=auth_token, verbose=False)
16
 
17
  total_runs = 0
18
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  class HuggingFaceDatasetSaver_custom(gr.HuggingFaceDatasetSaver):
21
  def _deserialize_components(
22
  self,
@@ -88,6 +128,7 @@ def generate_text(
88
  try:
89
  title, text, url = download_text_and_title(url)
90
  except Exception as e:
 
91
  title = None
92
  text = None
93
 
@@ -113,18 +154,13 @@ def generate_text(
113
  progress(0.5, desc="🤖 Leyendo noticia")
114
 
115
  try:
116
- temp = client.submit(
117
- url, # str in '🌐 URL de la noticia' Textbox component
118
- title, # str in '🌐 Título de la noticia' Textbox component
119
- text, # str in '📰 Cuerpo de la noticia' Textbox component
120
- mode, # float (numeric value between 0 and 100) in '🎚️ Nivel de resumen' Slider component
121
- api_name="/predict",
122
- )
123
-
124
- for o in temp:
125
- yield title, o, text
126
 
127
  except Exception as e:
 
128
  yield (
129
  "🤖 El servidor no se encuentra disponible.",
130
  "❌❌❌ Inténtalo de nuevo más tarde ❌❌❌",
@@ -136,7 +172,6 @@ def generate_text(
136
  "Error",
137
  )
138
 
139
- temp = temp.outputs()[-1]
140
  cache_handler.add_to_cache(
141
  url=url, title=title, text=text, summary_type=mode, summary=temp
142
  )
@@ -200,7 +235,7 @@ Para obtener solo la respuesta al clickbait, selecciona 100""",
200
  placeholder="Aquí aparecerá el resumen de la noticia.",
201
  ),
202
  ],
203
- #title="⚔️ Clickbait Fighter! ⚔️",
204
  thumbnail="https://huggingface.co/spaces/Iker/ClickbaitFighter/resolve/main/logo2.png",
205
  theme="JohnSmith9982/small_and_pretty",
206
  description="""
@@ -220,11 +255,10 @@ Para obtener solo la respuesta al clickbait, selecciona 100""",
220
  🧪 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!""",
221
  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.",
222
  cache_examples=False,
223
- concurrency_limit=1,
224
  allow_flagging="manual",
225
  flagging_options=[("👍", "correct"), ("👎", "incorrect")],
226
  flagging_callback=hf_writer,
227
  )
228
 
229
- demo.queue(max_size=None)
230
  demo.launch(share=False)
 
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 = "http://localhost:7861/generate"
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
+ "[/INST]",
38
+ "[INST]",
39
+ "### User:",
40
+ "### Assistant:",
41
+ "###",
42
+ ],
43
+ "stream": stream,
44
+ "api_key": API_KEY,
45
+ }
46
+ response = requests.post(api_url, headers=headers, json=json)
47
+ return response
48
+
49
+
50
+ def get_streaming_response(response: requests.Response) -> Iterable[List[str]]:
51
+ for chunk in response.iter_lines(
52
+ chunk_size=8192, decode_unicode=False, delimiter=b"\0"
53
+ ):
54
+ if chunk:
55
+ data = json.loads(chunk.decode("utf-8"))
56
+ output = data["text"]
57
+ yield output
58
+
59
+
60
  class HuggingFaceDatasetSaver_custom(gr.HuggingFaceDatasetSaver):
61
  def _deserialize_components(
62
  self,
 
128
  try:
129
  title, text, url = download_text_and_title(url)
130
  except Exception as e:
131
+ print(e)
132
  title = None
133
  text = None
134
 
 
154
  progress(0.5, desc="🤖 Leyendo noticia")
155
 
156
  try:
157
+ response = call_vllm_server(title, text, mode, stream=True)
158
+ for h in get_streaming_response(response):
159
+ temp = h[0]
160
+ yield title, temp, text
 
 
 
 
 
 
161
 
162
  except Exception as e:
163
+ print(e)
164
  yield (
165
  "🤖 El servidor no se encuentra disponible.",
166
  "❌❌❌ Inténtalo de nuevo más tarde ❌❌❌",
 
172
  "Error",
173
  )
174
 
 
175
  cache_handler.add_to_cache(
176
  url=url, title=title, text=text, summary_type=mode, summary=temp
177
  )
 
235
  placeholder="Aquí aparecerá el resumen de la noticia.",
236
  ),
237
  ],
238
+ # title="⚔️ Clickbait Fighter! ⚔️",
239
  thumbnail="https://huggingface.co/spaces/Iker/ClickbaitFighter/resolve/main/logo2.png",
240
  theme="JohnSmith9982/small_and_pretty",
241
  description="""
 
255
  🧪 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!""",
256
  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.",
257
  cache_examples=False,
 
258
  allow_flagging="manual",
259
  flagging_options=[("👍", "correct"), ("👎", "incorrect")],
260
  flagging_callback=hf_writer,
261
  )
262
 
263
+ demo.queue(max_size=None, concurrency_count=100)
264
  demo.launch(share=False)