File size: 8,719 Bytes
53bf50a
5efe001
2a3a970
460a080
e8a0f17
53bf50a
9b2d559
2a3a970
683284b
e8a0f17
5efe001
bf6da96
 
 
 
 
 
 
 
 
5efe001
bf6da96
 
 
e9d9124
8cb52d1
 
2a3a970
32a87d5
2bf0a50
8907f87
2bf0a50
2a3a970
 
2bf0a50
 
 
 
2a3a970
 
8cb52d1
 
 
2a3a970
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efe001
2a3a970
 
 
 
 
 
 
 
 
 
5efe001
 
683284b
 
 
 
 
5efe001
 
e78e7c2
2a18b06
5efe001
 
 
683284b
 
 
 
 
 
 
 
b7c9c79
d79b3e8
5efe001
 
 
 
 
 
d79b3e8
9352ec1
 
 
683284b
9352ec1
5efe001
 
 
 
 
683284b
 
9352ec1
5efe001
 
9352ec1
5a5168a
5efe001
65f249c
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
from __future__ import annotations
from typing import Iterable, Tuple
import gradio as gr
from gradio.themes.monochrome import Monochrome
import spaces
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForTokenClassification, pipeline
import os
import plotly.graph_objects as go

# Utility functions for color conversions and brightness adjustment
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)

monochrome = Monochrome()
auth_token = os.environ['HF_TOKEN']

# Load the tokenizer and models for the first pipeline
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)

# Load the tokenizer and models for the second pipeline
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)

# Load the tokenizer and models for the third pipeline
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)

# Define functions to process inputs
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) -> Tuple[float, float, float]:
    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 prediction1, prediction2, score

def generate_pie_chart(values: list, labels: list, title: str):
    fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.3)])
    fig.update_layout(title_text=title)
    file_path = "/tmp/pie_chart.html"
    fig.write_html(file_path)
    return file_path

@spaces.GPU
def all(text):
    ner_bin = process_ner(text, pipe_bin)
    ner_ext = process_ner(text, pipe_ext)
    int_count, ext_count, int_ext_ratio = process_classification(text, model1, model2, tokenizer1)
    
    # Create pie charts
    pie_chart_path_int_ext = generate_pie_chart([int_count, ext_count], ['Internal', 'External'], "Internal vs External Details")
    subclass_labels = [entity['entity'] for entity in ner_ext['entities']]
    subclass_values = [1] * len(subclass_labels)  # Each entity is counted once; adjust as needed for actual counts
    pie_chart_path_subclass = generate_pie_chart(subclass_values, subclass_labels, "Detail Subclasses")

    return ner_bin, ner_ext, f"{round(int_count, 1)}", f"{round(ext_count, 1)}", f"{round(int_ext_ratio, 2)}", pie_chart_path_int_ext, pie_chart_path_subclass

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?"],
]

# Define Gradio interface
iface = gr.Interface(
    fn=all,
    inputs=gr.Textbox(lines=5, label="Input Text", placeholder="Write about an experience"),
    outputs=[
        gr.HighlightedText(label="NER Binary"),
        gr.HighlightedText(label="NER External"),
        gr.Textbox(label="Internal Detail"),
        gr.Textbox(label="External Detail"),
        gr.Textbox(label="Ratio Int/Ext"),
        gr.HTML(label="Pie Chart of Internal vs External Details", elem_id="pie_chart_int_ext"),
        gr.HTML(label="Pie Chart of Subclass Details", elem_id="pie_chart_subclass"),
    ],
    theme=monochrome,
    examples=examples
)

# Launch the interface
iface.launch(debug=True)