AlGe commited on
Commit
5efe001
·
verified ·
1 Parent(s): 498ee48

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -113
app.py CHANGED
@@ -1,20 +1,16 @@
1
  from __future__ import annotations
2
- from typing import Iterable
3
 
4
  import gradio as gr
5
- from gradio.themes.base import Base
6
- from gradio.themes.soft import Soft
7
  from gradio.themes.monochrome import Monochrome
8
- from gradio.themes.default import Default
9
- from gradio.themes.utils import colors, fonts, sizes
10
-
11
  import spaces
12
  import torch
13
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForTokenClassification, pipeline
14
  import os
 
15
  import colorsys
16
- import time
17
 
 
18
  def hex_to_rgb(hex_color: str) -> tuple[int, int, int]:
19
  hex_color = hex_color.lstrip('#')
20
  return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
@@ -23,77 +19,12 @@ def rgb_to_hex(rgb_color: tuple[int, int, int]) -> str:
23
  return "#{:02x}{:02x}{:02x}".format(*rgb_color)
24
 
25
  def adjust_brightness(rgb_color: tuple[int, int, int], factor: float) -> tuple[int, int, int]:
26
- # Convert RGB to HSV, adjust V (value), convert back to RGB
27
  hsv_color = colorsys.rgb_to_hsv(*[v / 255.0 for v in rgb_color])
28
- new_v = max(0, min(hsv_color[2] * factor, 1)) # Ensure the value is within [0, 1]
29
  new_rgb = colorsys.hsv_to_rgb(hsv_color[0], hsv_color[1], new_v)
30
  return tuple(int(v * 255) for v in new_rgb)
31
 
32
-
33
- """
34
- class MPGPoster(Default):
35
- @staticmethod
36
- def create_color_shades(hex_color: str, brightness_control: float = 1.0) -> colors.Color:
37
- base_rgb = hex_to_rgb(hex_color)
38
- shades = {}
39
- # Define base brightness factors for shades
40
- base_factors = {
41
- "c50": 1.6, "c100": 1.4, "c200": 1.3,
42
- "c300": 1.2, "c400": 1, "c500": 0.8,
43
- "c600": 0.5, "c700": 0.35, "c800": 0.2,
44
- "c900": 0.15, "c950": 0.1
45
- }
46
- # Adjust brightness factors based on brightness_control
47
- factors = {shade: factor * brightness_control for shade, factor in base_factors.items()}
48
-
49
- for shade, factor in factors.items():
50
- new_rgb = adjust_brightness(base_rgb, factor)
51
- shades[shade] = rgb_to_hex(new_rgb)
52
- return colors.Color(**shades)
53
-
54
- def __init__(
55
- self,
56
- *,
57
- spacing_size: sizes.Size | str = sizes.spacing_md,
58
- 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,
59
- text_size: sizes.Size | str = sizes.text_lg,
60
- font: fonts.Font
61
- | str
62
- | Iterable[fonts.Font | str] = (
63
- fonts.GoogleFont("Jost"), # Changed here to "Jost"
64
- "ui-sans-serif",
65
- "sans-serif",
66
- ),
67
- font_mono: fonts.Font
68
- | str
69
- | Iterable[fonts.Font | str] = (
70
- fonts.GoogleFont("IBM Plex Mono"),
71
- "ui-monospace",
72
- "monospace",
73
- ),
74
- ):
75
- primary_hue = MPGPoster.create_color_shades("#f47317") #orange
76
- background_hue = MPGPoster.create_color_shades("#006c66") ##f6f6f6ff green
77
- secondary_dark_hue = MPGPoster.create_color_shades("#6ad5bc") #006c66
78
- #secondary_light_hue = MPGPoster.create_color_shades("#fbf22c") #6ad5bc
79
- #tertiary_highlight_hue = MPGPoster.create_color_shades("#6ad5bc") #fbf22c
80
-
81
- super().__init__(
82
- primary_hue=primary_hue,
83
- secondary_hue=secondary_dark_hue,
84
- neutral_hue=background_hue,
85
- spacing_size=spacing_size,
86
- radius_size=radius_size,
87
- text_size=text_size,
88
- font=font,
89
- font_mono=font_mono,
90
- )
91
-
92
- mpg_poster = MPGPoster()
93
-
94
- """
95
  monochrome = Monochrome()
96
-
97
  auth_token = os.environ['HF_TOKEN']
98
 
99
  # Load the tokenizer and models for the first pipeline
@@ -111,7 +42,6 @@ pipe_ext = pipeline("ner", model=model_ext, tokenizer=tokenizer_ext)
111
  # Load the tokenizer and models for the third pipeline
112
  model1 = AutoModelForSequenceClassification.from_pretrained("AlGe/deberta-v3-large_Int_segment", num_labels=1, token=auth_token)
113
  tokenizer1 = AutoTokenizer.from_pretrained("AlGe/deberta-v3-large_Int_segment", token=auth_token)
114
-
115
  model2 = AutoModelForSequenceClassification.from_pretrained("AlGe/deberta-v3-large_seq_ext", num_labels=1, token=auth_token)
116
 
117
  # Define functions to process inputs
@@ -142,7 +72,7 @@ def process_ner(text, pipeline):
142
 
143
  return {"text": text, "entities": entities}
144
 
145
- def process_classification(text, model1, model2, tokenizer1):
146
  inputs1 = tokenizer1(text, max_length=512, return_tensors='pt', truncation=True, padding=True)
147
 
148
  with torch.no_grad():
@@ -153,53 +83,50 @@ def process_classification(text, model1, model2, tokenizer1):
153
  prediction2 = outputs2[0].item()
154
  score = prediction1 / (prediction2 + prediction1)
155
 
156
- return f"{round(prediction1, 1)}", f"{round(prediction2, 1)}", f"{round(score, 2)}"
157
-
 
 
 
 
 
 
 
 
 
 
 
158
  @spaces.GPU
159
  def all(text):
160
- 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]
 
 
 
 
161
 
162
  examples = [
163
- ['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.'],
164
- ['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.'],
165
- ["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."],
166
- ['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.'],
167
- ["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?"],
168
- ]
169
 
170
  # Define Gradio interface
171
  iface = gr.Interface(
172
  fn=all,
173
- 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 ..."),
174
  outputs=[
175
- gr.HighlightedText(label="Binary Sequence Classification",
176
- color_map={
177
- "External": "#6ad5bcff",
178
- "Internal": "#ee8bacff"}
179
- ),
180
- gr.HighlightedText(label="Extended Sequence Classification",
181
- color_map = {
182
- "INTemothou": "#FF7F50", # Coral
183
- "INTpercept": "#FF4500", # OrangeRed
184
- "INTtime": "#FF6347", # Tomato
185
- "INTplace": "#FFD700", # Gold
186
- "INTevent": "#FFA500", # Orange
187
-
188
- # EXT classes should be different from INT classes
189
- "EXTsemantic": "#4682B4", # SteelBlue
190
- "EXTrepetition": "#5F9EA0", # CadetBlue
191
- "EXTother": "#00CED1", # DarkTurquoise
192
- }
193
- ),
194
- gr.Label(label="Internal Detail Count"),
195
- gr.Label(label="External Detail Count"),
196
- gr.Label(label="Approximated Internal Detail Ratio")
197
  ],
198
- title="Scoring Demo",
199
- 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.",
200
- examples = examples,
201
- theme= monochrome #"soft" #monochrome #mpg_poster
202
  )
203
 
204
- # Launch the combined interface
205
- iface.launch()
 
1
  from __future__ import annotations
2
+ from typing import Iterable, Tuple
3
 
4
  import gradio as gr
 
 
5
  from gradio.themes.monochrome import Monochrome
 
 
 
6
  import spaces
7
  import torch
8
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForTokenClassification, pipeline
9
  import os
10
+ import matplotlib.pyplot as plt
11
  import colorsys
 
12
 
13
+ # Utility functions for color conversions and brightness adjustment
14
  def hex_to_rgb(hex_color: str) -> tuple[int, int, int]:
15
  hex_color = hex_color.lstrip('#')
16
  return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
 
19
  return "#{:02x}{:02x}{:02x}".format(*rgb_color)
20
 
21
  def adjust_brightness(rgb_color: tuple[int, int, int], factor: float) -> tuple[int, int, int]:
 
22
  hsv_color = colorsys.rgb_to_hsv(*[v / 255.0 for v in rgb_color])
23
+ new_v = max(0, min(hsv_color[2] * factor, 1))
24
  new_rgb = colorsys.hsv_to_rgb(hsv_color[0], hsv_color[1], new_v)
25
  return tuple(int(v * 255) for v in new_rgb)
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  monochrome = Monochrome()
 
28
  auth_token = os.environ['HF_TOKEN']
29
 
30
  # Load the tokenizer and models for the first pipeline
 
42
  # Load the tokenizer and models for the third pipeline
43
  model1 = AutoModelForSequenceClassification.from_pretrained("AlGe/deberta-v3-large_Int_segment", num_labels=1, token=auth_token)
44
  tokenizer1 = AutoTokenizer.from_pretrained("AlGe/deberta-v3-large_Int_segment", token=auth_token)
 
45
  model2 = AutoModelForSequenceClassification.from_pretrained("AlGe/deberta-v3-large_seq_ext", num_labels=1, token=auth_token)
46
 
47
  # Define functions to process inputs
 
72
 
73
  return {"text": text, "entities": entities}
74
 
75
+ def process_classification(text, model1, model2, tokenizer1) -> Tuple[float, float, float]:
76
  inputs1 = tokenizer1(text, max_length=512, return_tensors='pt', truncation=True, padding=True)
77
 
78
  with torch.no_grad():
 
83
  prediction2 = outputs2[0].item()
84
  score = prediction1 / (prediction2 + prediction1)
85
 
86
+ return prediction1, prediction2, score
87
+
88
+ def generate_pie_chart(internal_count: float, external_count: float):
89
+ labels = 'Internal', 'External'
90
+ sizes = [internal_count, external_count]
91
+ colors = ['#ff9999','#66b3ff']
92
+ fig, ax = plt.subplots()
93
+ ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
94
+ plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
95
+ file_path = "/tmp/pie_chart.png"
96
+ plt.savefig(file_path)
97
+ return file_path
98
+
99
  @spaces.GPU
100
  def all(text):
101
+ ner_bin = process_ner(text, pipe_bin)
102
+ ner_ext = process_ner(text, pipe_ext)
103
+ int_count, ext_count, int_ext_ratio = process_classification(text, model1, model2, tokenizer1)
104
+ pie_chart_path = generate_pie_chart(int_count, ext_count)
105
+ return ner_bin, ner_ext, f"{round(int_count, 1)}", f"{round(ext_count, 1)}", f"{round(int_ext_ratio, 2)}", pie_chart_path
106
 
107
  examples = [
108
+ ['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.'],
109
+ ['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.'],
110
+ ["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."],
111
+ ['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.'],
112
+ ["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?"],
113
+ ]
114
 
115
  # Define Gradio interface
116
  iface = gr.Interface(
117
  fn=all,
118
+ 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 ..."),
119
  outputs=[
120
+ gr.HighlightedText(label="NER Binary"),
121
+ gr.HighlightedText(label="NER External"),
122
+ gr.Textbox(label="Internal Detail"),
123
+ gr.Textbox(label="External Detail"),
124
+ gr.Textbox(label="Ratio Int/Ext"),
125
+ gr.Image(type="filepath", label="Pie Chart of Internal vs External Details"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  ],
127
+ theme=monochrome,
128
+ examples=examples
 
 
129
  )
130
 
131
+ # Launch the interface
132
+ iface.launch(debug=True)