Token Classification
Transformers
ONNX
Safetensors
bert
subtitles
live-captioning
text-compression
llmlingua-2
deletion-only
Instructions to use marcosremar2/ucast-subtitle-compressor with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use marcosremar2/ucast-subtitle-compressor with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="marcosremar2/ucast-subtitle-compressor")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("marcosremar2/ucast-subtitle-compressor") model = AutoModelForTokenClassification.from_pretrained("marcosremar2/ucast-subtitle-compressor", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download common.py from marcosremar2/ucast-subtitle-compressor: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/marcosremar2/ucast-subtitle-compressor/resolve/main/common.py
- Command line
-
hf download hf://marcosremar2/ucast-subtitle-compressor/common.py
-
curl -L -o common.py https://huggingface.co/marcosremar2/ucast-subtitle-compressor/resolve/main/common.py
11.4 kB
| """Shared by labelling, training and evaluation: words, alignment and how kept words are written back.""" | |
| import re | |
| import unicodedata | |
| END = re.compile(r"[.!?…]+[\"'»”)\]]*$") | |
| NEG = { | |
| "pt": {"não", "nunca", "nem", "nada", "ninguém", "nenhum", "nenhuma", "jamais"}, | |
| "fr": {"ne", "n'", "pas", "jamais", "rien", "personne", "aucun", "aucune", "plus", "ni"}, | |
| "es": {"no", "nunca", "nada", "nadie", "ningún", "ninguna", "ninguno", "jamás", "ni"}, | |
| "en": {"not", "no", "never", "nothing", "nobody", "none", "n't", "neither", "nor"}, | |
| } | |
| def words(text): | |
| return text.split() | |
| def norm(w): | |
| w = unicodedata.normalize("NFC", w).lower() | |
| return re.sub(r"^[\W_]+|[\W_]+$", "", w) | |
| def align(src_words, out_text): | |
| """Labels (1 keep, 0 drop) when out_text is src_words with words deleted, else None. | |
| Punctuation and case may differ; every output word must match the next source word in order.""" | |
| out = [norm(w) for w in words(out_text)] | |
| out = [w for w in out if w] | |
| labels, j = [0] * len(src_words), 0 | |
| for i, w in enumerate(src_words): | |
| if j < len(out) and norm(w) == out[j]: | |
| labels[i], j = 1, j + 1 | |
| return labels if j == len(out) and out else None | |
| def render(src_words, keep): | |
| """Writes the kept words as text: a sentence end carried by a dropped word moves to the | |
| last kept word, a trailing comma before it goes, and a new sentence starts with a capital.""" | |
| out, cap_next, gap = [], True, [] | |
| for w, k in zip(src_words, keep): | |
| if k: | |
| # "X, [aside], Y" -> "X Y": an aside cut between two commas takes the first comma along | |
| if gap and out and out[-1].endswith(",") and gap[-1].endswith(",") and not END.search(gap[-1]): | |
| out[-1] = out[-1][:-1] | |
| gap = [] | |
| if cap_next and w[:1].islower(): | |
| w = w[:1].upper() + w[1:] | |
| out.append(w) | |
| cap_next = bool(END.search(w)) | |
| else: | |
| gap.append(w) | |
| m = END.search(w) | |
| if m and out and not END.search(out[-1]): | |
| out[-1] = out[-1].rstrip(",;:—-") + m.group(0) | |
| cap_next = True | |
| if out and not END.search(out[-1]): | |
| out[-1] = out[-1].rstrip(",;:—-") + "." | |
| return " ".join(out) | |
| def facts(text, lang): | |
| """Numbers, names (capitalised words not starting a sentence) and negations of a text.""" | |
| ws = words(text) | |
| found = set() | |
| for i, w in enumerate(ws): | |
| n = norm(w) | |
| if not n: | |
| continue | |
| if any(c.isdigit() for c in n): | |
| found.add(n) | |
| elif n in NEG.get(lang, set()) or (lang == "en" and n.endswith("n't")): | |
| found.add(n) | |
| elif w[:1].isupper() and i > 0 and not END.search(ws[i - 1]) and len(n) > 1: | |
| found.add(n) | |
| return found | |
| # ---- protection: words that can never be deleted, and sentences that can never go whole ---- | |
| NUMBERS = { | |
| "pt": "dois duas três quatro cinco seis sete oito nove dez onze doze treze catorze quatorze quinze dezesseis dezasseis dezessete dezassete dezoito dezenove dezanove vinte trinta quarenta cinquenta sessenta setenta oitenta noventa cem cento duzentos duzentas trezentos quatrocentos quinhentos mil milhão milhões bilhão bilhões bilião primeiro primeira segundo segunda terceiro terceira metade dobro dúzia", | |
| "fr": "deux trois quatre cinq six sept huit neuf dix onze douze treize quatorze quinze seize vingt trente quarante cinquante soixante cent cents mille million millions milliard milliards premier première deuxième troisième moitié double douzaine", | |
| "es": "dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciséis diecisiete dieciocho diecinueve veinte treinta cuarenta cincuenta sesenta setenta ochenta noventa cien ciento doscientos doscientas trescientos mil millón millones primero primera segundo segunda tercero tercera mitad doble docena", | |
| "en": "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty thirty forty fifty sixty seventy eighty ninety hundred thousand million millions billion billions first second third half double dozen", | |
| } | |
| PERCENT = {"pt": "cento porcento", "fr": "pourcent", "es": "ciento porciento", "en": "percent"} | |
| TIME = { | |
| "pt": "hoje amanhã ontem segunda-feira terça-feira quarta-feira quinta-feira sexta-feira sábado domingo segunda terça quarta quinta sexta janeiro fevereiro março abril maio junho julho agosto setembro outubro novembro dezembro", | |
| "fr": "aujourd'hui demain hier lundi mardi mercredi jeudi vendredi samedi dimanche janvier février mars avril mai juin juillet août septembre octobre novembre décembre", | |
| "es": "hoy mañana ayer lunes martes miércoles jueves viernes sábado domingo enero febrero marzo abril mayo junio julio agosto septiembre octubre noviembre diciembre", | |
| "en": "today tomorrow yesterday monday tuesday wednesday thursday friday saturday sunday january february march april may june july august september october november december", | |
| } | |
| _SETS = {lang: set(NUMBERS[lang].split()) | set(PERCENT[lang].split()) | set(TIME[lang].split()) | NEG[lang] | |
| for lang in NUMBERS} | |
| def sentences(ws): | |
| """Word indices of each sentence.""" | |
| out, cur = [], [] | |
| for i, w in enumerate(ws): | |
| cur.append(i) | |
| if END.search(w): | |
| out.append(cur) | |
| cur = [] | |
| if cur: | |
| out.append(cur) | |
| return out | |
| def protected(ws, lang): | |
| """1 for each word that must stay: digits, numbers and dates said in words, negations, names | |
| (a capital not starting a sentence) and acronyms; plus the short word right before one | |
| ("até terça", "de deux degrés") so it does not end up alone.""" | |
| p = [0] * len(ws) | |
| vocab = _SETS.get(lang, set()) | |
| for i, w in enumerate(ws): | |
| n = norm(w) | |
| if not n: | |
| continue | |
| starts = i == 0 or bool(END.search(ws[i - 1])) or ws[i - 1][-1:] in "\"«“:" | |
| if (any(c.isdigit() for c in n) or n in vocab or n.split("'")[-1] in vocab | |
| or (lang == "en" and n.endswith("n't")) | |
| or (len(n) > 1 and n.isupper() and n.isalpha()) | |
| or (w[:1].isupper() and not starts and len(n) > 1)): | |
| p[i] = 1 | |
| nums = set(NUMBERS.get(lang, "").split()) | |
| for i in range(len(ws) - 1): # the unit after a number: "deux degrés", "five hours", "doze por cento" | |
| n = norm(ws[i]) | |
| if (any(c.isdigit() for c in n) or n in nums) and not END.search(ws[i]): | |
| p[i + 1] = 1 | |
| if norm(ws[i + 1]) in {"por", "pour", "per"} and i + 2 < len(ws): | |
| p[i + 2] = 1 | |
| for i in range(1, len(ws)): | |
| prev = norm(ws[i - 1]) | |
| if p[i] and not p[i - 1] and prev and len(prev) <= 4 and ws[i - 1].islower() and not END.search(ws[i - 1]): | |
| p[i - 1] = 1 | |
| return p | |
| def decide(ws, probs, lang, word_drop=0.3, sentence_drop=0.35, min_share=0.5): | |
| """Keep/drop for each word from the model's keep probabilities, safe by construction: | |
| - a protected word always stays; | |
| - a sentence goes whole only when its mean keep probability is under sentence_drop and it has | |
| no protected word and is not a question; the most likely sentence always stays; | |
| - inside a sentence that stays, a word goes only when the model is sure (prob < word_drop); | |
| - a sentence never ends up as a fragment: if fewer than min_share of its words would stay, it goes | |
| whole (when it could) or stays whole (protected, a question, or the only/best sentence).""" | |
| prot = protected(ws, lang) | |
| sents = sentences(ws) | |
| score = [sum(probs[i] for i in s) / len(s) for s in sents] | |
| best = max(range(len(sents)), key=lambda j: score[j]) | |
| keep = [0] * len(ws) | |
| seen = set() | |
| for j, s in enumerate(sents): | |
| key = " ".join(norm(ws[i]) for i in s) | |
| if key in seen: # said again word for word: the first copy already carries it | |
| continue | |
| seen.add(key) | |
| safe = any(prot[i] for i in s) or ws[s[-1]].rstrip("\"'»”)]").endswith("?") | |
| if score[j] < sentence_drop and not safe and j != best: | |
| continue | |
| ks = [int(prot[i] or probs[i] >= word_drop) for i in s] | |
| if sum(ks) < min_share * len(s): | |
| ks = [1] * len(s) if (safe or j == best) else [0] * len(s) | |
| for i, k in zip(s, ks): | |
| keep[i] = k | |
| return keep | |
| def lost_protected(ws, keep, lang): | |
| """Protected words absent from the output (must always be empty). A word dropped with a sentence | |
| said twice is not lost: the first copy still has it.""" | |
| kept = {norm(w) for w, k in zip(ws, keep) if k} | |
| return [w for w, p, k in zip(ws, protected(ws, lang), keep) if p and not k and norm(w) not in kept] | |
| # ---- unit decoding: only whole units go (round 1) ---- | |
| FILLERS = { | |
| "pt": "bom então né tipo assim olha olhem enfim pois aliás ok okay hum ahn eh é", | |
| "fr": "alors bon euh ben donc voilà enfin bref quoi hein ok okay", | |
| "es": "bueno pues este o sea vale entonces bien eh ok okay", | |
| "en": "so well um uh like okay ok right now actually basically", | |
| } | |
| _FILL = {lang: set(v.split()) for lang, v in FILLERS.items()} | |
| SPLIT = re.compile(r"[,;:]$|^[–—(]|[)–—]$") | |
| def units(ws, sent): | |
| """Splits one sentence (word indices) into comma/dash/parenthesis segments.""" | |
| out, cur = [], [] | |
| for i in sent: | |
| w = ws[i] | |
| if w in ("–", "—") and cur: | |
| out.append(cur); cur = [] | |
| cur.append(i) | |
| if SPLIT.search(w) and w not in ("–", "—"): | |
| out.append(cur); cur = [] | |
| if cur: | |
| out.append(cur) | |
| return out | |
| def decide_units(ws, probs, lang, unit_drop=0.2, sentence_drop=0.2, filler_drop=0.5): | |
| """Keep/drop where only whole units can go: a whole sentence, a whole comma/dash segment, or a | |
| filler word from the list. A unit goes only when the model is sure (mean keep prob under its | |
| threshold) and it holds nothing protected; a sentence never loses its last segment, a | |
| question never goes, a sentence said twice keeps its first copy, and the best sentence stays.""" | |
| prot = protected(ws, lang) | |
| sents = sentences(ws) | |
| score = [sum(probs[i] for i in s) / len(s) for s in sents] | |
| best = max(range(len(sents)), key=lambda j: score[j]) | |
| keep = [1] * len(ws) | |
| seen = set() | |
| for j, s in enumerate(sents): | |
| key = " ".join(norm(ws[i]) for i in s) | |
| question = ws[s[-1]].rstrip("\"'»”)]").endswith("?") | |
| if key in seen or (score[j] < sentence_drop and not any(prot[i] for i in s) and not question and j != best): | |
| for i in s: | |
| keep[i] = 0 | |
| seen.add(key) | |
| continue | |
| seen.add(key) | |
| segs = units(ws, s) | |
| for u in segs: | |
| if len(segs) > 1 and not any(prot[i] for i in u) and sum(probs[i] for i in u) / len(u) < unit_drop: | |
| for i in u: | |
| keep[i] = 0 | |
| if not any(keep[i] for i in s): # never drop the last segment this way | |
| for i in s: | |
| keep[i] = 1 | |
| for i in s: # single fillers ("bom,", "euh", "so") | |
| if keep[i] and norm(ws[i]) in _FILL.get(lang, set()) and probs[i] < filler_drop and not prot[i]: | |
| keep[i] = 0 | |
| return keep | |