Spaces:
Running
Running
File size: 9,029 Bytes
1130e24 cf9ad46 1130e24 04f8f8b 1130e24 70be539 1130e24 70be539 af68a82 1130e24 853f29a 1130e24 82b9aeb 67fd23e b2b1d1f 67fd23e 9e29fa0 69cec82 3424c6f 67fd23e 69cec82 1130e24 af68a82 1130e24 ecdbfcf 70be539 ecdbfcf 2180861 70be539 2180861 70be539 2180861 70be539 1130e24 70be539 2180861 1130e24 70be539 1130e24 70be539 90fa7ec 82b9aeb 5f6b004 70be539 d1e7332 7d912ec 70be539 73ee479 853f29a 73ee479 70be539 3cc9ea6 82b9aeb 3cc9ea6 a1eb2dd 70be539 703612e 70be539 1130e24 3e91901 1130e24 af68a82 fb1a253 af68a82 fb1a253 af68a82 fb1a253 853f29a af68a82 882055b 0f6a4f6 882055b 1130e24 af68a82 882055b af68a82 55b014b af68a82 1130e24 af68a82 70be539 8ea1705 a1dac96 8ea1705 a1dac96 cdbd963 8ea1705 70be539 90fa7ec 70be539 57caf39 8ea1705 57caf39 8ea1705 2b41a25 2f654f8 3e91901 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
import gradio as gr
import spaces
import os
import torch
import numpy as np
import pandas as pd
from transformers import AutoModelForSequenceClassification
from transformers import AutoTokenizer
import torch.nn.functional as F
from huggingface_hub import HfApi
from collections import defaultdict
from label_dicts import (CAP_MEDIA_NUM_DICT, CAP_MEDIA_LABEL_NAMES,
CAP_MIN_NUM_DICT, CAP_MIN_LABEL_NAMES,
CAP_MIN_MEDIA_NUM_DICT)
from .utils import is_disk_full, release_model
HF_TOKEN = os.environ["hf_read"]
languages = [
"Multilingual",
]
domains = {
"media": "media"
}
NUM_TOP_CLASSES = 5
CAP_MEDIA_CODES = list(CAP_MEDIA_NUM_DICT.values())
CAP_MIN_CODES = list(CAP_MIN_NUM_DICT.values())
major_index_to_id = {i: code for i, code in enumerate(CAP_MEDIA_CODES)}
minor_id_to_index = {code: i for i, code in enumerate(CAP_MIN_CODES)}
minor_index_to_id = {i: code for i, code in enumerate(CAP_MIN_CODES)}
major_to_minor_map = defaultdict(list)
for code in CAP_MIN_CODES:
major_id = int(str(code)[:-2])
major_to_minor_map[major_id].append(code)
major_to_minor_map = dict(major_to_minor_map)
def normalize_probs(probs: dict) -> dict:
total = sum(probs.values())
return {k: v / total for k, v in probs.items()}
def check_huggingface_path(checkpoint_path: str):
try:
hf_api = HfApi(token=HF_TOKEN)
hf_api.model_info(checkpoint_path, token=HF_TOKEN)
return True
except:
return False
def build_huggingface_path(language: str, domain: str, hierarchical: bool):
if hierarchical:
return ("poltextlab/xlm-roberta-large-pooled-cap-media", "poltextlab/xlm-roberta-large-pooled-cap-minor-v3")
else:
return "poltextlab/xlm-roberta-large-pooled-cap-media-minor"
#@spaces.GPU(duration=30)
def predict(text, major_model_id, minor_model_id, tokenizer_id, HF_TOKEN=None):
device = torch.device("cpu")
# Load major and minor models + tokenizer
major_model = AutoModelForSequenceClassification.from_pretrained(
major_model_id,
low_cpu_mem_usage=True,
device_map="auto",
offload_folder="offload",
token=HF_TOKEN
).to(device)
minor_model = AutoModelForSequenceClassification.from_pretrained(
minor_model_id,
low_cpu_mem_usage=True,
device_map="auto",
offload_folder="offload",
token=HF_TOKEN
).to(device)
tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)
# Tokenize input
inputs = tokenizer(text, max_length=256, truncation=True, padding="do_not_pad", return_tensors="pt").to(device)
# Predict major topic
major_model.eval()
with torch.no_grad():
major_logits = major_model(**inputs).logits
major_probs = F.softmax(major_logits, dim=-1)
major_probs_np = major_probs.cpu().numpy().flatten()
top_major_index = int(np.argmax(major_probs_np))
top_major_id = major_index_to_id[top_major_index]
# Default: show major topic predictions
filtered_probs = {
i: float(major_probs_np[i])
for i in np.argsort(major_probs_np)[::-1]
}
filtered_probs = normalize_probs(filtered_probs)
output_pred = {
f"[{major_index_to_id[k]}] {CAP_MEDIA_LABEL_NAMES[major_index_to_id[k]]}": v
for k, v in sorted(filtered_probs.items(), key=lambda item: item[1], reverse=True)
}
# If eligible for minor prediction
if top_major_id in major_to_minor_map:
valid_minor_ids = major_to_minor_map[top_major_id]
minor_model.eval()
with torch.no_grad():
minor_logits = minor_model(**inputs).logits
minor_probs = F.softmax(minor_logits, dim=-1)
release_model(major_model, major_model_id)
release_model(minor_model, minor_model_id)
print(minor_probs) # debug
# Restrict to valid minor codes
valid_indices = [minor_id_to_index[mid] for mid in valid_minor_ids if mid in minor_id_to_index]
filtered_probs = {minor_index_to_id[i]: float(minor_probs[0][i]) for i in valid_indices}
print(filtered_probs) # debug
filtered_probs = normalize_probs(filtered_probs)
print(filtered_probs) # debug
output_pred = {
f"[{top_major_id}] {CAP_MEDIA_LABEL_NAMES[top_major_id]} [{k}] {CAP_MIN_LABEL_NAMES[k]}": v
for k, v in sorted(filtered_probs.items(), key=lambda item: item[1], reverse=True)
}
output_info = f'<p style="text-align: center; display: block">Prediction used <a href="https://huggingface.co/{major_model_id}">{major_model_id}</a> and <a href="https://huggingface.co/{minor_model_id}">{minor_model_id}</a>.</p>'
interpretation_info = """
## How to Interpret These Values (Hierarchical Classification)
This method returns either:
- A list of **major (media) topic confidences**, or
- A list of **minor topic confidences**.
In the case of minor topics, the values are the confidences for minor topics **within a given major topic**, and they are **normalized to sum to 1**.
"""
return interpretation_info, output_pred, output_info
def predict_flat(text, model_id, tokenizer_id, HF_TOKEN=None):
device = torch.device("cpu")
# Load JIT-traced model
jit_model_path = f"/data/jit_models/{model_id.replace('/', '_')}.pt"
model = torch.jit.load(jit_model_path).to(device)
model.eval()
# Load tokenizer (still regular HF)
tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)
# Tokenize input
inputs = tokenizer(
text,
max_length=256,
truncation=True,
padding="do_not_pad",
return_tensors="pt"
)
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
output = model(inputs["input_ids"], inputs["attention_mask"])
print(output) # debug
logits = output["logits"]
release_model(model, model_id)
probs = torch.nn.functional.softmax(logits, dim=1).cpu().numpy().flatten()
top_indices = np.argsort(probs)[::-1][:10]
CAP_MIN_MEDIA_LABEL_NAMES = CAP_MEDIA_LABEL_NAMES | CAP_MIN_LABEL_NAMES
output_pred = {}
for i in top_indices:
code = CAP_MIN_MEDIA_NUM_DICT[i]
prob = probs[i]
if code in CAP_MEDIA_LABEL_NAMES:
# Media (major) topic
label = CAP_MEDIA_LABEL_NAMES[code]
display = f"[{code}] {label}"
else:
# Minor topic
major_code = code // 100
major_label = CAP_MEDIA_LABEL_NAMES[major_code]
minor_label = CAP_MIN_LABEL_NAMES[code]
display = f"[{major_code}] {major_label} [{code}] {minor_label}"
output_pred[display] = prob
interpretation_info = """
## How to Interpret These Values (Flat Classification)
This method returns predictions made by a single model. Both media codes and minor topics may appear in the output list. **Only the top 10 most confident labels are displayed**.
"""
output_info = f'<p style="text-align: center; display: block">Prediction was made using the <a href="https://huggingface.co/{model_id}">{model_id}</a> model.</p>'
return interpretation_info, output_pred, output_info
def predict_cap(tmp, method, text, language, domain):
if is_disk_full():
os.system('rm -rf /data/models*')
os.system('rm -r ~/.cache/huggingface/hub')
domain = domains[domain]
if method == "Hierarchical Classification":
major_model_id, minor_model_id = build_huggingface_path(language, domain, True)
tokenizer_id = "xlm-roberta-large"
return predict(text, major_model_id, minor_model_id, tokenizer_id)
else:
model_id = build_huggingface_path(language, domain, False)
tokenizer_id = "xlm-roberta-large"
return predict_flat(text, model_id, tokenizer_id)
description = """
You can choose between two approaches for making predictions:
**1. Hierarchical Classification**
First, the model predicts a **major topic**. Then, a second model selects the most probable **subtopic** from within that major topic's category.
**2. Flat Classification (single model)**
A single model directly predicts the most relevant label from all available classes (both media and minor topics).
"""
demo = gr.Interface(
title="CAP Media/Minor Topics Babel Demo",
fn=predict_cap,
inputs=[gr.Markdown(description),
gr.Radio(
choices=["Hierarchical Classification", "Flat Classification"],
label="Prediction Mode",
value="Hierarchical Classification"
),
gr.Textbox(lines=6, label="Input"),
gr.Dropdown(languages, label="Language", value=languages[0]),
gr.Dropdown(domains.keys(), label="Domain", value=list(domains.keys())[0])],
outputs=[gr.Markdown(), gr.Label(label="Output"), gr.Markdown()])
|