Spaces:
Runtime error
Runtime error
File size: 7,587 Bytes
53bf50a a0ade0a 2a3a970 a0ade0a 460a080 a0ade0a e8a0f17 53bf50a 2a3a970 036e563 75c27f0 bf036e1 e8a0f17 036e563 b1dcc65 036e563 b1dcc65 d0f20ab 036e563 b1dcc65 bf6da96 6b0ab1a bf6da96 e9d9124 a0ade0a 8cb52d1 2bf0a50 2a3a970 a0ade0a 2a3a970 6b0ab1a 5ba216a 6b0ab1a 5ba216a 6b0ab1a 6f0c78d 2a3a970 745604f a0ade0a a8497b9 886193f a9c9e52 ac8f612 a9c9e52 5ba216a 886193f a9c9e52 b49c174 a0ade0a 5e6d454 3fda0f5 a0ade0a cd8444d b1dcc65 c4c09ea 443d088 75c27f0 7a3ed1a 443d088 7a3ed1a b1dcc65 5e6d454 443d088 b1dcc65 5e6d454 443d088 5e6d454 b1dcc65 c4c09ea b1dcc65 5e6d454 b1dcc65 5e6d454 b1dcc65 5e6d454 b7c9c79 5e6d454 745604f 5e6d454 cd8444d d79b3e8 3a9b2f3 9352ec1 a0ade0a 9352ec1 a0ade0a b779906 5e6d454 9352ec1 a0ade0a 9352ec1 5a5168a b1dcc65 |
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 |
from __future__ import annotations
from typing import Iterable, List, Dict, Tuple
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
import os
import io
import re
import colorsys
import numpy as np
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForTokenClassification, pipeline
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from wordcloud import WordCloud
from PIL import Image
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']
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)
def process_ner(text: str, pipeline) -> dict:
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'],
"tokens": [token['word']]
}
else:
current_entity['end'] = token['end']
current_entity['score'] = max(current_entity['score'], token['score'])
current_entity['tokens'].append(token['word'])
if current_entity is not None:
entities.append(current_entity)
return {"text": text, "entities": entities}
def generate_charts(ner_output_ext: dict) -> Tuple[go.Figure, np.ndarray]:
entities_ext = [entity['entity'] for entity in ner_output_ext['entities']]
# Counting entities for extended classification
entity_counts_ext = {entity: entities_ext.count(entity) for entity in set(entities_ext)}
ext_labels = list(entity_counts_ext.keys())
ext_sizes = list(entity_counts_ext.values())
ext_color_map = {
"INTemothou": "#FF7F50", # Coral
"INTpercept": "#FF4500", # OrangeRed
"INTtime": "#FF6347", # Tomato
"INTplace": "#FFD700", # Gold
"INTevent": "#FFA500", # Orange
"EXTsemantic": "#4682B4", # SteelBlue
"EXTrepetition": "#5F9EA0", # CadetBlue
"EXTother": "#00CED1", # DarkTurquoise
}
ext_colors = [ext_color_map.get(label, "#FFFFFF") for label in ext_labels]
# Create pie chart for extended classification
fig1 = go.Figure(data=[go.Pie(labels=ext_labels, values=ext_sizes, textinfo='label+percent', hole=.3, marker=dict(colors=ext_colors))])
fig1.update_layout(
template='plotly_dark',
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)'
)
# Generate word cloud
wordcloud_image = generate_wordcloud(ner_output_ext['entities'], ext_color_map, "dh3.img")
return fig1, wordcloud_image
def generate_wordcloud(entities: List[Dict], color_map: Dict[str, str], image_path: str) -> np.ndarray:
mask_image = np.array(Image.open(image_path))
token_texts = []
token_scores = []
token_types = []
for entity in entities:
for token in entity['tokens']:
# Remove any leading non-alphanumeric characters
cleaned_token = re.sub(r'^\W+', '', token)
token_texts.append(cleaned_token)
token_scores.append(entity['score'])
token_types.append(entity['entity'])
print(f"{cleaned_token} ({entity['entity']}): {entity['score']}")
# Create a dictionary for word cloud
word_freq = {text: score for text, score in zip(token_texts, token_scores)}
def color_func(word, font_size, position, orientation, random_state=None, **kwargs):
entity_type = next((t for t, w in zip(token_types, token_texts) if w == word), None)
return color_map.get(entity_type, "#FFFFFF")
wordcloud = WordCloud(width=800, height=400, background_color='#121212', mask=mask_image, color_func=color_func).generate_from_frequencies(word_freq)
# Convert to image array
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.tight_layout(pad=0)
# Convert plt to numpy array
plt_image = plt.gcf()
plt_image.canvas.draw()
image_array = np.frombuffer(plt_image.canvas.tostring_rgb(), dtype=np.uint8)
image_array = image_array.reshape(plt_image.canvas.get_width_height()[::-1] + (3,))
plt.close()
return image_array
@spaces.GPU
def all(text: str):
ner_output_ext = process_ner(text, pipe_ext)
pie_chart, wordcloud_image = generate_charts(ner_output_ext)
return (ner_output_ext, pie_chart, wordcloud_image)
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.'],
]
iface = gr.Interface(
fn=all,
inputs=gr.Textbox(lines=5, label="Input Text", placeholder="Write about how your breakfast went or anything else that happened or might happen to you ..."),
outputs=[
gr.HighlightedText(label="Extended Sequence Classification",
color_map={
"INTemothou": "#FF7F50", # Coral
"INTpercept": "#FF4500", # OrangeRed
"INTtime": "#FF6347", # Tomato
"INTplace": "#FFD700", # Gold
"INTevent": "#FFA500", # Orange
"EXTsemantic": "#4682B4", # SteelBlue
"EXTrepetition": "#5F9EA0", # CadetBlue
"EXTother": "#00CED1", # DarkTurquoise
}
),
gr.Plot(label="Extended SeqClass Entity Distribution Pie Chart"),
gr.Image(label="Entity Word Cloud")
],
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() |