|
from __future__ import annotations |
|
from typing import Iterable |
|
|
|
import gradio as gr |
|
from gradio.themes.base import Base |
|
from gradio.themes.soft import Soft |
|
from gradio.themes.monochrome import Monochrome |
|
from gradio.themes.default import Default |
|
from gradio.themes.utils import colors, fonts, sizes |
|
|
|
import spaces |
|
import torch |
|
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForTokenClassification, pipeline |
|
import os |
|
import colorsys |
|
import time |
|
|
|
def hex_to_rgb(hex_color: str) -> tuple[int, int, int]: |
|
hex_color = hex_color.lstrip('#') |
|
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) |
|
|
|
def rgb_to_hex(rgb_color: tuple[int, int, int]) -> str: |
|
return "#{:02x}{:02x}{:02x}".format(*rgb_color) |
|
|
|
def adjust_brightness(rgb_color: tuple[int, int, int], factor: float) -> tuple[int, int, int]: |
|
|
|
hsv_color = colorsys.rgb_to_hsv(*[v / 255.0 for v in rgb_color]) |
|
new_v = max(0, min(hsv_color[2] * factor, 1)) |
|
new_rgb = colorsys.hsv_to_rgb(hsv_color[0], hsv_color[1], new_v) |
|
return tuple(int(v * 255) for v in new_rgb) |
|
|
|
|
|
""" |
|
class MPGPoster(Default): |
|
@staticmethod |
|
def create_color_shades(hex_color: str, brightness_control: float = 1.0) -> colors.Color: |
|
base_rgb = hex_to_rgb(hex_color) |
|
shades = {} |
|
# Define base brightness factors for shades |
|
base_factors = { |
|
"c50": 1.6, "c100": 1.4, "c200": 1.3, |
|
"c300": 1.2, "c400": 1, "c500": 0.8, |
|
"c600": 0.5, "c700": 0.35, "c800": 0.2, |
|
"c900": 0.15, "c950": 0.1 |
|
} |
|
# Adjust brightness factors based on brightness_control |
|
factors = {shade: factor * brightness_control for shade, factor in base_factors.items()} |
|
|
|
for shade, factor in factors.items(): |
|
new_rgb = adjust_brightness(base_rgb, factor) |
|
shades[shade] = rgb_to_hex(new_rgb) |
|
return colors.Color(**shades) |
|
|
|
def __init__( |
|
self, |
|
*, |
|
spacing_size: sizes.Size | str = sizes.spacing_md, |
|
radius_size: sizes.Size | str = sizes.Size( 0, 0, 0, 0, 0, 0, 0, 0), # Set radius size to 0 for hard edges sizes.radius_md, |
|
text_size: sizes.Size | str = sizes.text_lg, |
|
font: fonts.Font |
|
| str |
|
| Iterable[fonts.Font | str] = ( |
|
fonts.GoogleFont("Jost"), # Changed here to "Jost" |
|
"ui-sans-serif", |
|
"sans-serif", |
|
), |
|
font_mono: fonts.Font |
|
| str |
|
| Iterable[fonts.Font | str] = ( |
|
fonts.GoogleFont("IBM Plex Mono"), |
|
"ui-monospace", |
|
"monospace", |
|
), |
|
): |
|
primary_hue = MPGPoster.create_color_shades("#f47317") #orange |
|
background_hue = MPGPoster.create_color_shades("#006c66") ##f6f6f6ff green |
|
secondary_dark_hue = MPGPoster.create_color_shades("#6ad5bc") #006c66 |
|
#secondary_light_hue = MPGPoster.create_color_shades("#fbf22c") #6ad5bc |
|
#tertiary_highlight_hue = MPGPoster.create_color_shades("#6ad5bc") #fbf22c |
|
|
|
super().__init__( |
|
primary_hue=primary_hue, |
|
secondary_hue=secondary_dark_hue, |
|
neutral_hue=background_hue, |
|
spacing_size=spacing_size, |
|
radius_size=radius_size, |
|
text_size=text_size, |
|
font=font, |
|
font_mono=font_mono, |
|
) |
|
|
|
mpg_poster = MPGPoster() |
|
|
|
""" |
|
|
|
auth_token = os.environ['HF_TOKEN'] |
|
|
|
|
|
tokenizer_bin = AutoTokenizer.from_pretrained("AlGe/deberta-v3-large_token", token=auth_token) |
|
model_bin = AutoModelForTokenClassification.from_pretrained("AlGe/deberta-v3-large_token", token=auth_token) |
|
tokenizer_bin.model_max_length = 512 |
|
pipe_bin = pipeline("ner", model=model_bin, tokenizer=tokenizer_bin) |
|
|
|
|
|
tokenizer_ext = AutoTokenizer.from_pretrained("AlGe/deberta-v3-large_AIS-token", token=auth_token) |
|
model_ext = AutoModelForTokenClassification.from_pretrained("AlGe/deberta-v3-large_AIS-token", token=auth_token) |
|
tokenizer_ext.model_max_length = 512 |
|
pipe_ext = pipeline("ner", model=model_ext, tokenizer=tokenizer_ext) |
|
|
|
|
|
model1 = AutoModelForSequenceClassification.from_pretrained("AlGe/deberta-v3-large_Int_segment", num_labels=1, token=auth_token) |
|
tokenizer1 = AutoTokenizer.from_pretrained("AlGe/deberta-v3-large_Int_segment", token=auth_token) |
|
|
|
model2 = AutoModelForSequenceClassification.from_pretrained("AlGe/deberta-v3-large_seq_ext", num_labels=1, token=auth_token) |
|
|
|
|
|
def process_ner(text, pipeline): |
|
output = pipeline(text) |
|
entities = [] |
|
current_entity = None |
|
|
|
for token in output: |
|
entity_type = token['entity'][2:] |
|
entity_prefix = token['entity'][:1] |
|
|
|
if current_entity is None or entity_type != current_entity['entity'] or (entity_prefix == 'B' and entity_type == current_entity['entity']): |
|
if current_entity is not None: |
|
entities.append(current_entity) |
|
current_entity = { |
|
"entity": entity_type, |
|
"start": token['start'], |
|
"end": token['end'], |
|
"score": token['score'] |
|
} |
|
else: |
|
current_entity['end'] = token['end'] |
|
current_entity['score'] = max(current_entity['score'], token['score']) |
|
|
|
if current_entity is not None: |
|
entities.append(current_entity) |
|
|
|
return {"text": text, "entities": entities} |
|
|
|
def process_classification(text, model1, model2, tokenizer1): |
|
inputs1 = tokenizer1(text, max_length=512, return_tensors='pt', truncation=True, padding=True) |
|
|
|
with torch.no_grad(): |
|
outputs1 = model1(**inputs1) |
|
outputs2 = model2(**inputs1) |
|
|
|
prediction1 = outputs1[0].item() |
|
prediction2 = outputs2[0].item() |
|
score = prediction1 / (prediction2 + prediction1) |
|
|
|
return f"{round(prediction1, 1)}", f"{round(prediction2, 1)}", f"{round(score, 2)}" |
|
|
|
@spaces.GPU |
|
def all(text): |
|
return process_ner(text, pipe_bin), process_ner(text, pipe_ext), process_classification(text, model1, model2, tokenizer1)[0], process_classification(text, model1, model2, tokenizer1)[1], process_classification(text, model1, model2, tokenizer1)[2] |
|
|
|
examples = [ |
|
['Bevor ich meinen Hund kaufte bin ich immer alleine durch den Park gelaufen. Gestern war ich aber mit dem Hund losgelaufen. Das Wetter war sehr schön, nicht wie sonst im Winter. Ich weiß nicht genau. Mir fällt sonst nichts dazu ein. Wir trafen auf mehrere Spaziergänger. Ein Mann mit seinem Kind. Das Kind hat ein Eis gegessen.'], |
|
['Also, ich kann mir total vorstellen, dass ich in so zwei Jahren eine mega Geburtstagsparty für meinen besten Freund organisieren werde. Also, das wird echt krass, ich schwöre es dir. Ich werde eine coole Location finden, wahrscheinlich so ein Haus am See oder so, und dann lade ich echt alle seine Freunde und Familie ein. Und dann, das wird der Hammer, ich werde eine Band organisieren, die so seine ganze Lieblingsmusik spielt, weißt du? Und dann, weil ich ja keine Lust habe, selbst zu kochen, hol ich mir so einen professionellen Catering-Service, die dann für alle Gäste kochen. Na ja, ich hoff mal, dass das Wetter mitspielt und wir alle draußen feiern können. Ich sag dir, das wird echt ne unvergessliche Feier, und mein Freund wird ausflippen vor Überraschung, echt jetzt.'], |
|
["So, I really imagine that in two years, I'll finally be living my dream and writing a novel. I'll find a quiet place where I can fully concentrate on writing. I'll tell a story that really engages me and that I want to share with others. I'll draw inspiration from my experiences and the people around me, just like in real life. I'll spend many hours putting my thoughts on paper and bringing my characters to life. Well, I hope that readers also find my story fascinating; that would be really cool."], |
|
['Oh mein Gott, ich muss dir diese total lustige Geschichte aus meiner Schulzeit erzählen! Du wirst es nicht glauben. Also, ich kam eines Tages zu spät zur Schule, richtig? Du weißt, wie das ist, man ist in Eile und achtet nicht wirklich darauf. Ich habe einfach ein Paar Schuhe gegriffen und bin aus dem Haus gerannt. Erst als ich in der Schule war und mich zum Mittagessen hinsetzte, bemerkte ich, dass ich zwei völlig unterschiedliche Schuhe anhatte! Ich hatte einen schwarzen und einen weißen Turnschuh an. Und ich mache keine Witze, die Leute haben es sofort bemerkt. Ein Typ namens Tommy hat mich Mismatch Mike genannt und bald haben alle mitgemacht. Oh Mann, ich war damals so peinlich berührt! Jetzt finde ich es einfach nur witzig und frage mich, wie mir das nicht aufgefallen ist. Das ist eine dieser Geschichten, die ich jetzt auf Partys erzähle, und die Leute finden es total lustig.'], |
|
["You know, this conversation reminded me of an incredible experience I had at a music festival in college. I'll never forget it. It was a rainy day, but we didn't care, and the band that was playing was my absolute favorite. Even though we were all soaked, the crowd kept on dancing and singing along. The energy was incredible, and I remember feeling so connected to everyone around me. It was as if the rain made the whole experience even more magical. I was surrounded by friends, and we all shared this special moment together. It was one of the best moments of my life, and I still get goosebumps when I think about it. Sometimes, it's the unexpected things that create the most amazing memories, you know?"], |
|
] |
|
|
|
|
|
iface = gr.Interface( |
|
fn=all, |
|
inputs=gr.Textbox(lines=5, label="Input Text",placeholder="Write about how your breakfast went or anything else that happend or might happen to you ..."), |
|
outputs=[ |
|
gr.HighlightedText(label="Binary Sequence Classification", |
|
color_map={ |
|
"External": "#6ad5bcff", |
|
"Internal": "#ee8bacff"} |
|
), |
|
gr.HighlightedText(label="Extended Sequence Classification", |
|
color_map = { |
|
"INTemothou": "#FF7F50", |
|
"INTpercept": "#FF4500", |
|
"INTtime": "#FF6347", |
|
"INTplace": "#FFD700", |
|
"INTevent": "#FFA500", |
|
|
|
|
|
"EXTsemantic": "#4682B4", |
|
"EXTrepetition": "#5F9EA0", |
|
"EXTother": "#00CED1", |
|
} |
|
), |
|
gr.Label(label="Internal Detail Count"), |
|
gr.Label(label="External Detail Count"), |
|
gr.Label(label="Approximated Internal Detail Ratio") |
|
], |
|
title="Scoring Demo", |
|
description="Autobiographical Memory Analysis: This demo combines two text - and two sequence classification models to showcase our automated Autobiographical Interview scoring method. Submit a narrative to see the results.", |
|
examples = examples, |
|
theme= monochrome |
|
) |
|
|
|
|
|
iface.launch() |