albertmartinez commited on
Commit
3aec51f
·
1 Parent(s): 722190b

perf(app): refactor Gradio UI and optimize model loading

Browse files

Replace nested Interfaces with native Blocks, stream ALL-tab results
with progress, cache small models, and limit large models to one in
memory. Add torch inference optimizations and remove unused pydantic.

Files changed (2) hide show
  1. app.py +208 -183
  2. requirements.txt +0 -1
app.py CHANGED
@@ -1,20 +1,22 @@
1
  import gc
2
  import logging
 
3
  import threading
4
- from typing import Dict, List, Literal, Optional, Tuple
5
 
6
  import gradio as gr
7
- from pydantic import BaseModel, Field
8
- from transformers import pipeline
9
 
10
- # Logging configuration
11
  logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
13
 
14
- # Constants
15
  MAX_LENGTH = 512
16
  TOP_K = 16
17
  InputFormat = Literal["plain", "openalex"]
 
 
 
18
  EXAMPLE_TEXT = (
19
  "To respond to these new challenges PSV has been encouraged to develop strong links "
20
  "with business and enterprises, to cover remote areas and to cater for less affluent "
@@ -34,7 +36,14 @@ EXAMPLE_OPENALEX_ABSTRACT = (
34
  "isolated from the coastal waters of Korea. For each of the 14 morphospecies, the "
35
  "nuclear-encoded small subunit ribosomal RNA gene was sequenced and analyzed."
36
  )
37
- MODELS: Dict[str, Dict[str, str]] = {
 
 
 
 
 
 
 
38
  "bert": {
39
  "path": "albertmartinez/bert-sdg-classification",
40
  "input_format": "plain",
@@ -61,220 +70,236 @@ MODELS: Dict[str, Dict[str, str]] = {
61
  },
62
  }
63
 
64
- class ClassificationResult(BaseModel):
65
- """Model for classification results."""
66
- label: str = Field(..., description="Classification label")
67
- score: float = Field(..., description="Classification score")
68
-
69
  _model_lock = threading.Lock()
70
- _loaded_model: Optional[Tuple[str, pipeline]] = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
- def _unload_model() -> None:
73
- """Allibera el model actual de memòria."""
74
- global _loaded_model
75
- if _loaded_model is None:
76
  return
77
- name, model = _loaded_model
78
- logger.info("Descarregant model %s", name)
79
  del model
80
- _loaded_model = None
81
  gc.collect()
82
- try:
83
- import torch
84
 
85
- if torch.cuda.is_available():
86
- torch.cuda.empty_cache()
87
- except ImportError:
88
- pass
89
 
90
- def get_model(name: str) -> pipeline:
91
- """Carrega un model sota demanda i manté només un model actiu en memòria."""
92
- global _loaded_model
93
  if name not in MODELS:
94
- raise ValueError(f"Model desconegut: {name}")
95
 
96
  with _model_lock:
97
- if _loaded_model and _loaded_model[0] == name:
98
- return _loaded_model[1]
 
 
99
 
100
- _unload_model()
101
- logger.info("Carregant model %s...", name)
102
  try:
103
- model = pipeline("text-classification", model=MODELS[name]["path"])
104
- except Exception as e:
105
- logger.error("Error carregant model %s: %s", name, e)
106
  raise
107
- _loaded_model = (name, model)
108
- return model
 
 
 
 
 
 
109
 
110
  def format_openalex_input(title: str, abstract: str = "") -> str:
111
- """Formata títol i resum segons el dataset sdg-openalex."""
112
  title = title.strip()
113
  abstract = abstract.strip()
114
  if not title and not abstract:
115
- raise ValueError("Cal indicar almenys el títol o el resum")
116
  if abstract:
117
  return f"<TITLE>{title}</TITLE><ABSTRACT>{abstract}</ABSTRACT>"
118
  return f"<TITLE>{title}</TITLE>"
119
 
 
120
  def prepare_model_input(
121
  model_name: str,
122
  text: str,
123
  title: str = "",
124
  abstract: str = "",
125
  ) -> str:
126
- """Prepara l'entrada segons el format esperat per cada model."""
127
- input_format: InputFormat = MODELS[model_name]["input_format"] # type: ignore[assignment]
128
- if input_format == "openalex":
129
  return format_openalex_input(title or text, abstract)
130
  return text
131
 
132
- def validate_input(text: str) -> bool:
133
- """Validate input text."""
134
- if not text or not isinstance(text, str):
135
- return False
136
- if len(text.strip()) == 0:
137
- return False
138
- return True
139
-
140
- def classify_text(text: str, model: pipeline) -> Dict[str, float]:
141
- """
142
- Classify text using the specified model.
143
-
144
- Args:
145
- text: Text to classify
146
- model: Classification model
147
-
148
- Returns:
149
- Dictionary with labels and their scores
150
- """
151
- if not validate_input(text):
152
- raise ValueError("Invalid text input")
153
-
154
- try:
155
  result = model(text, top_k=TOP_K, truncation=True, max_length=MAX_LENGTH)
156
- return {p["label"]: p["score"] for p in result}
157
- except Exception as e:
158
- logger.error(f"Error in classification: {str(e)}")
159
- raise
160
-
161
- def classify_all(text: str, title: str = "", abstract: str = "") -> List[Dict[str, float]]:
162
- """
163
- Classifica el text amb tots els models disponibles.
164
-
165
- Args:
166
- text: Text pla per als models estàndard
167
- title: Títol per al model OpenAlex
168
- abstract: Resum per al model OpenAlex
169
-
170
- Returns:
171
- Llista de diccionaris amb prediccions de cada model
172
- """
173
- if not validate_input(text) and not validate_input(title) and not validate_input(abstract):
174
- raise ValueError("Invalid text input")
175
-
176
- try:
177
- return [
178
- classify_text(
179
- prepare_model_input(name, text, title, abstract),
180
- get_model(name),
181
- )
182
- for name in MODELS
183
- ]
184
- except Exception as e:
185
- logger.error(f"Error in multiple classification: {str(e)}")
186
- raise
187
-
188
- def create_interface(model_name: str) -> gr.Interface:
189
- """Crea una interfície Gradio per a un model concret."""
190
- input_format: InputFormat = MODELS[model_name]["input_format"] # type: ignore[assignment]
191
-
192
- if input_format == "openalex":
193
- return gr.Interface(
194
- fn=lambda title, abstract: classify_text(
195
- format_openalex_input(title, abstract),
196
- get_model(model_name),
197
- ),
198
- inputs=[
199
- gr.Textbox(
200
- label="Title",
201
- placeholder="Article title...",
202
- ),
203
- gr.Textbox(
204
- lines=5,
205
- label="Abstract",
206
- placeholder="Article abstract (optional)...",
207
- ),
208
- ],
209
- outputs=gr.Label(label="Top SDG Predicted"),
210
- title=f"{model_name.upper()} SDG classification",
211
- description=(
212
- "Enter title and abstract in OpenAlex format "
213
- "(<TITLE></TITLE><ABSTRACT></ABSTRACT>). "
214
- "Trained on albertmartinez/sdg-openalex."
215
- ),
216
- examples=[[EXAMPLE_OPENALEX_TITLE, EXAMPLE_OPENALEX_ABSTRACT]],
217
- flagging_mode="never",
218
- api_name=f"classify_{model_name}",
219
  )
 
220
 
221
- return gr.Interface(
222
- fn=lambda text: classify_text(text, get_model(model_name)),
223
- inputs=gr.Textbox(
224
- lines=2,
225
- label="Text",
226
- placeholder="Enter text here...",
227
- ),
228
- outputs=gr.Label(label="Top SDG Predicted"),
229
- title=f"{model_name.upper()} SDG classification",
230
- description="Enter text and see the classification results!",
231
- examples=[[EXAMPLE_TEXT]],
232
- flagging_mode="never",
233
- api_name=f"classify_{model_name}",
234
- )
235
 
236
- # Create main interface
237
- ifaceall = gr.Interface(
238
- fn=classify_all,
239
- inputs=[
240
- gr.Textbox(
241
- lines=2,
242
- label="Text",
243
- placeholder="Enter text here for standard models...",
244
- ),
245
- gr.Textbox(
246
- label="Title (OpenAlex model)",
247
- placeholder="Article title for xlm-roberta-large-openalex...",
248
- ),
249
- gr.Textbox(
250
- lines=3,
251
- label="Abstract (OpenAlex model)",
252
- placeholder="Article abstract for xlm-roberta-large-openalex (optional)...",
253
- ),
254
- ],
255
- outputs=[gr.Label(label=name) for name in MODELS],
256
- title="SDG text classification",
257
- description=(
258
- "Enter plain text for standard models. For the OpenAlex model, use the "
259
- "Title/Abstract fields (<TITLE></TITLE><ABSTRACT></ABSTRACT>). "
260
- "Models are loaded on demand; the ALL tab may take longer on first use."
261
- ),
262
- examples=[[EXAMPLE_TEXT, EXAMPLE_OPENALEX_TITLE, EXAMPLE_OPENALEX_ABSTRACT]],
263
- flagging_mode="never",
264
- api_name="classify_all_models",
265
- )
266
 
267
- # Create individual interfaces
268
- interfaces = [ifaceall] + [create_interface(name) for name in MODELS]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
- # Create main interface with tabs
271
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
272
- gr.TabbedInterface(
273
- interface_list=interfaces,
274
- tab_names=["ALL"] + list(MODELS.keys()),
275
- title="Sustainable Development Goals (SDG) Text Classifier App"
276
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
  if __name__ == "__main__":
279
- logger.info(f"Gradio version: {gr.__version__}")
280
  demo.launch()
 
1
  import gc
2
  import logging
3
+ import os
4
  import threading
5
+ from typing import Dict, Generator, List, Literal, Optional, Tuple, TypedDict
6
 
7
  import gradio as gr
8
+ import torch
9
+ from transformers import Pipeline, pipeline
10
 
 
11
  logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
13
 
 
14
  MAX_LENGTH = 512
15
  TOP_K = 16
16
  InputFormat = Literal["plain", "openalex"]
17
+ SMALL_MODELS = frozenset({"bert", "bert-multilingual", "distilbert-multilingual"})
18
+ DEVICE = 0 if torch.cuda.is_available() else -1
19
+
20
  EXAMPLE_TEXT = (
21
  "To respond to these new challenges PSV has been encouraged to develop strong links "
22
  "with business and enterprises, to cover remote areas and to cater for less affluent "
 
36
  "isolated from the coastal waters of Korea. For each of the 14 morphospecies, the "
37
  "nuclear-encoded small subunit ribosomal RNA gene was sequenced and analyzed."
38
  )
39
+
40
+
41
+ class ModelConfig(TypedDict):
42
+ path: str
43
+ input_format: InputFormat
44
+
45
+
46
+ MODELS: Dict[str, ModelConfig] = {
47
  "bert": {
48
  "path": "albertmartinez/bert-sdg-classification",
49
  "input_format": "plain",
 
70
  },
71
  }
72
 
 
 
 
 
 
73
  _model_lock = threading.Lock()
74
+ _small_cache: Dict[str, Pipeline] = {}
75
+ _loaded_large: Optional[Tuple[str, Pipeline]] = None
76
+
77
+ torch.set_grad_enabled(False)
78
+ if DEVICE == -1:
79
+ torch.set_num_threads(min(4, os.cpu_count() or 4))
80
+
81
+
82
+ def _create_pipeline(name: str) -> Pipeline:
83
+ logger.info("Loading model %s on device %s", name, DEVICE)
84
+ return pipeline(
85
+ "text-classification",
86
+ model=MODELS[name]["path"],
87
+ device=DEVICE,
88
+ )
89
 
90
+
91
+ def _unload_large_model() -> None:
92
+ global _loaded_large
93
+ if _loaded_large is None:
94
  return
95
+ name, model = _loaded_large
96
+ logger.info("Unloading large model %s", name)
97
  del model
98
+ _loaded_large = None
99
  gc.collect()
100
+ if torch.cuda.is_available():
101
+ torch.cuda.empty_cache()
102
 
 
 
 
 
103
 
104
+ def get_model(name: str) -> Pipeline:
105
+ """Load models on demand. Small models stay cached; only one large model in memory."""
 
106
  if name not in MODELS:
107
+ raise ValueError(f"Unknown model: {name}")
108
 
109
  with _model_lock:
110
+ if name in _small_cache:
111
+ return _small_cache[name]
112
+ if _loaded_large and _loaded_large[0] == name:
113
+ return _loaded_large[1]
114
 
 
 
115
  try:
116
+ loaded = _create_pipeline(name)
117
+ except Exception as exc:
118
+ logger.error("Failed to load model %s: %s", name, exc)
119
  raise
120
+
121
+ if name in SMALL_MODELS:
122
+ _small_cache[name] = loaded
123
+ else:
124
+ _unload_large_model()
125
+ _loaded_large = (name, loaded)
126
+ return loaded
127
+
128
 
129
  def format_openalex_input(title: str, abstract: str = "") -> str:
 
130
  title = title.strip()
131
  abstract = abstract.strip()
132
  if not title and not abstract:
133
+ raise gr.Error("Provide at least a title or an abstract for the OpenAlex model.")
134
  if abstract:
135
  return f"<TITLE>{title}</TITLE><ABSTRACT>{abstract}</ABSTRACT>"
136
  return f"<TITLE>{title}</TITLE>"
137
 
138
+
139
  def prepare_model_input(
140
  model_name: str,
141
  text: str,
142
  title: str = "",
143
  abstract: str = "",
144
  ) -> str:
145
+ if MODELS[model_name]["input_format"] == "openalex":
 
 
146
  return format_openalex_input(title or text, abstract)
147
  return text
148
 
149
+
150
+ def has_valid_input(text: str, title: str = "", abstract: str = "") -> bool:
151
+ return any(part.strip() for part in (text, title, abstract) if isinstance(part, str))
152
+
153
+
154
+ def classify_text(text: str, model: Pipeline) -> Dict[str, float]:
155
+ if not text.strip():
156
+ raise gr.Error("Input text cannot be empty.")
157
+
158
+ with torch.inference_mode():
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  result = model(text, top_k=TOP_K, truncation=True, max_length=MAX_LENGTH)
160
+ return {item["label"]: item["score"] for item in result}
161
+
162
+
163
+ def classify_single(model_name: str, text: str) -> Dict[str, float]:
164
+ return classify_text(text, get_model(model_name))
165
+
166
+
167
+ def classify_openalex(model_name: str, title: str, abstract: str) -> Dict[str, float]:
168
+ return classify_text(format_openalex_input(title, abstract), get_model(model_name))
169
+
170
+
171
+ def classify_all(
172
+ text: str,
173
+ title: str = "",
174
+ abstract: str = "",
175
+ progress: gr.Progress = gr.Progress(),
176
+ ) -> Generator[Tuple[Dict[str, float], ...], None, None]:
177
+ if not has_valid_input(text, title, abstract):
178
+ raise gr.Error("Provide text for standard models and/or title/abstract for OpenAlex.")
179
+
180
+ model_names = list(MODELS)
181
+ pending: List[Optional[Dict[str, float]]] = [None] * len(model_names)
182
+
183
+ for index, name in enumerate(model_names):
184
+ progress((index, len(model_names)), desc=f"Running {name}...")
185
+ pending[index] = classify_text(
186
+ prepare_model_input(name, text, title, abstract),
187
+ get_model(name),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  )
189
+ yield tuple(result or {} for result in pending)
190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
+ def build_demo() -> gr.Blocks:
193
+ with gr.Blocks(
194
+ theme=gr.themes.Soft(),
195
+ title="Sustainable Development Goals (SDG) Text Classifier App",
196
+ ) as demo:
197
+ gr.Markdown(
198
+ "# Sustainable Development Goals (SDG) Text Classifier\n"
199
+ "Classify scientific and general text against the 17 UN SDGs. "
200
+ "Models load on demand to reduce memory usage on Hugging Face Spaces."
201
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
+ with gr.Tabs():
204
+ with gr.Tab("ALL"):
205
+ gr.Markdown(
206
+ "Use **Text** for standard models. "
207
+ "Use **Title/Abstract** for the OpenAlex model "
208
+ "(`<TITLE></TITLE><ABSTRACT></ABSTRACT>`)."
209
+ )
210
+ with gr.Row():
211
+ all_text = gr.Textbox(
212
+ lines=4,
213
+ label="Text",
214
+ placeholder="Enter text for standard models...",
215
+ scale=2,
216
+ )
217
+ with gr.Column(scale=1):
218
+ all_title = gr.Textbox(
219
+ label="Title (OpenAlex model)",
220
+ placeholder="Article title...",
221
+ )
222
+ all_abstract = gr.Textbox(
223
+ lines=3,
224
+ label="Abstract (OpenAlex model)",
225
+ placeholder="Article abstract (optional)...",
226
+ )
227
+ all_btn = gr.Button("Classify with all models", variant="primary")
228
+ all_outputs = [gr.Label(label=name) for name in MODELS]
229
+ gr.Examples(
230
+ examples=[[EXAMPLE_TEXT, EXAMPLE_OPENALEX_TITLE, EXAMPLE_OPENALEX_ABSTRACT]],
231
+ inputs=[all_text, all_title, all_abstract],
232
+ )
233
+ all_btn.click(
234
+ fn=classify_all,
235
+ inputs=[all_text, all_title, all_abstract],
236
+ outputs=all_outputs,
237
+ api_name="classify_all_models",
238
+ )
239
 
240
+ for model_name, config in MODELS.items():
241
+ with gr.Tab(model_name):
242
+ gr.Markdown(f"### {model_name.upper()} SDG classification")
243
+
244
+ if config["input_format"] == "openalex":
245
+ title_input = gr.Textbox(
246
+ label="Title",
247
+ placeholder="Article title...",
248
+ )
249
+ abstract_input = gr.Textbox(
250
+ lines=5,
251
+ label="Abstract",
252
+ placeholder="Article abstract (optional)...",
253
+ info="Trained on albertmartinez/sdg-openalex.",
254
+ )
255
+ output = gr.Label(label="Top SDG Predicted")
256
+ run_btn = gr.Button("Classify", variant="primary")
257
+ gr.Examples(
258
+ examples=[[EXAMPLE_OPENALEX_TITLE, EXAMPLE_OPENALEX_ABSTRACT]],
259
+ inputs=[title_input, abstract_input],
260
+ )
261
+ run_btn.click(
262
+ fn=lambda title, abstract, name=model_name: classify_openalex(
263
+ name, title, abstract
264
+ ),
265
+ inputs=[title_input, abstract_input],
266
+ outputs=output,
267
+ api_name=f"classify_{model_name}",
268
+ )
269
+ title_input.submit(
270
+ fn=lambda title, abstract, name=model_name: classify_openalex(
271
+ name, title, abstract
272
+ ),
273
+ inputs=[title_input, abstract_input],
274
+ outputs=output,
275
+ )
276
+ else:
277
+ text_input = gr.Textbox(
278
+ lines=4,
279
+ label="Text",
280
+ placeholder="Enter text here...",
281
+ )
282
+ output = gr.Label(label="Top SDG Predicted")
283
+ run_btn = gr.Button("Classify", variant="primary")
284
+ gr.Examples(examples=[[EXAMPLE_TEXT]], inputs=text_input)
285
+ run_btn.click(
286
+ fn=lambda text, name=model_name: classify_single(name, text),
287
+ inputs=text_input,
288
+ outputs=output,
289
+ api_name=f"classify_{model_name}",
290
+ )
291
+ text_input.submit(
292
+ fn=lambda text, name=model_name: classify_single(name, text),
293
+ inputs=text_input,
294
+ outputs=output,
295
+ )
296
+
297
+ return demo
298
+
299
+
300
+ demo = build_demo()
301
+ demo.queue(default_concurrency_limit=1)
302
 
303
  if __name__ == "__main__":
304
+ logger.info("Gradio version: %s", gr.__version__)
305
  demo.launch()
requirements.txt CHANGED
@@ -1,4 +1,3 @@
1
  transformers>=4.30.0
2
  torch>=2.0.0
3
  numpy>=1.24.0
4
- pydantic>=2.7.4,<3.0.0
 
1
  transformers>=4.30.0
2
  torch>=2.0.0
3
  numpy>=1.24.0