Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,54 +9,57 @@ History_size = 5
|
|
| 9 |
MODELS = {
|
| 10 |
"Русский (rubert-tiny)": "cointegrated/rubert-tiny-sentiment-balanced",
|
| 11 |
"Twitter-roBERTa": "cardiffnlp/twitter-roberta-base-sentiment-latest"
|
| 12 |
-
|
| 13 |
}
|
| 14 |
|
| 15 |
_pipes = {}
|
| 16 |
|
| 17 |
-
#фу
|
| 18 |
def get_pipe(key):
|
| 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 |
def obr_file(file_obj, model_key):
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
try:
|
| 60 |
if path.endswith(".txt"):
|
| 61 |
with open(file_obj.name, "r", encoding="utf-8", errors="ignore") as f:
|
| 62 |
texts = [x.strip() for x in f.read().splitlines() if x.strip()]
|
|
@@ -64,73 +67,67 @@ def obr_file(file_obj, model_key):
|
|
| 64 |
df = pd.read_csv(file_obj.name)
|
| 65 |
col = "text" if "text" in df.columns else df.columns[0]
|
| 66 |
texts = df[col].astype(str).tolist()
|
| 67 |
-
|
| 68 |
return pd.DataFrame({"error": [f"Ошибка чтения файла: {e}"]})
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
| 82 |
|
| 83 |
with gr.Blocks() as demo:
|
| 84 |
-
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
|
| 90 |
-
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
|
| 97 |
state = gr.State([])
|
| 98 |
box = gr.Textbox(label="История запросов (последние 5)", lines=5)
|
| 99 |
|
| 100 |
btn.click(
|
| 101 |
analyze_text,
|
| 102 |
-
inputs
|
| 103 |
-
outputs
|
| 104 |
).then(
|
| 105 |
lambda h: "\n".join(h),
|
| 106 |
-
inputs
|
| 107 |
-
outputs
|
| 108 |
)
|
| 109 |
|
| 110 |
gr.Markdown("# Пакетная обработка (TXT/CSV)")
|
| 111 |
-
file_in = gr.File(label
|
| 112 |
bbtn = gr.Button("Обработать файл")
|
| 113 |
-
obtn = gr.
|
| 114 |
|
| 115 |
bbtn.click(obr_file, inputs=[file_in, model_choice], outputs=obtn)
|
|
|
|
| 116 |
gr.Examples(
|
| 117 |
examples=[
|
| 118 |
["Мне очень понравился этот фильм, всё отлично!", "Русский (rubert-tiny)"],
|
| 119 |
["Это худший опыт в моей жизни.", "Русский (rubert-tiny)"],
|
| 120 |
-
["The app is amazing!", "
|
| 121 |
-
["This is terrible and buggy.", "
|
| 122 |
],
|
| 123 |
inputs=[text_input, model_choice],
|
| 124 |
label="Примеры"
|
| 125 |
)
|
| 126 |
|
| 127 |
-
demo.launch()
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
| 9 |
MODELS = {
|
| 10 |
"Русский (rubert-tiny)": "cointegrated/rubert-tiny-sentiment-balanced",
|
| 11 |
"Twitter-roBERTa": "cardiffnlp/twitter-roberta-base-sentiment-latest"
|
|
|
|
| 12 |
}
|
| 13 |
|
| 14 |
_pipes = {}
|
| 15 |
|
| 16 |
+
# функция выбора конкретной модели
|
| 17 |
def get_pipe(key):
|
| 18 |
+
if key not in _pipes:
|
| 19 |
+
_pipes[key] = pipeline("sentiment-analysis", model=MODELS[key])
|
| 20 |
+
return _pipes[key] # ← ВАЖНО: вернуть пайплайн
|
| 21 |
+
|
| 22 |
+
# анализ текста с историей
|
| 23 |
+
def analyze_text(text, model_key, history):
|
| 24 |
+
start = time.time()
|
| 25 |
+
|
| 26 |
+
if text is None or not text.strip():
|
| 27 |
+
return "Ошибка: пустой ввод", "", 0.0, history
|
| 28 |
+
|
| 29 |
+
text = text.strip()
|
| 30 |
+
if len(text) > MAX_CHARS:
|
| 31 |
+
return "Ошибка: текст слишком длинный", "", 0.0, history
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
a = get_pipe(model_key)
|
| 35 |
+
res = a(text)[0]
|
| 36 |
+
label = res["label"]
|
| 37 |
+
score = round(float(res["score"]), 3)
|
| 38 |
+
except Exception as e:
|
| 39 |
+
return f"Ошибка модели: {e}", "", 0.0, history
|
| 40 |
+
|
| 41 |
+
latency = round(time.time() - start, 3)
|
| 42 |
+
record = f"[{model_key}] {text[:80]}... → {label} ({score}), {latency}s"
|
| 43 |
+
|
| 44 |
+
if not history:
|
| 45 |
+
history = []
|
| 46 |
+
|
| 47 |
+
history = history[-(History_size - 1):]
|
| 48 |
+
history.append(record)
|
| 49 |
+
|
| 50 |
+
return label, score, latency, history
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# функция для обработки файла
|
| 54 |
def obr_file(file_obj, model_key):
|
| 55 |
+
if file_obj is None:
|
| 56 |
+
return pd.DataFrame({"error": ["Файл не загружен"]})
|
| 57 |
+
|
| 58 |
+
path = file_obj.name.lower()
|
| 59 |
+
if not (path.endswith(".txt") or path.endswith(".csv")):
|
| 60 |
+
return pd.DataFrame({"error": ["Поддерживаются только .txt и .csv"]})
|
| 61 |
+
|
| 62 |
+
try:
|
|
|
|
| 63 |
if path.endswith(".txt"):
|
| 64 |
with open(file_obj.name, "r", encoding="utf-8", errors="ignore") as f:
|
| 65 |
texts = [x.strip() for x in f.read().splitlines() if x.strip()]
|
|
|
|
| 67 |
df = pd.read_csv(file_obj.name)
|
| 68 |
col = "text" if "text" in df.columns else df.columns[0]
|
| 69 |
texts = df[col].astype(str).tolist()
|
| 70 |
+
except Exception as e:
|
| 71 |
return pd.DataFrame({"error": [f"Ошибка чтения файла: {e}"]})
|
| 72 |
+
|
| 73 |
+
a = get_pipe(model_key)
|
| 74 |
+
rows = []
|
| 75 |
+
|
| 76 |
+
for t in texts:
|
| 77 |
+
t = t[:MAX_CHARS]
|
| 78 |
+
res = a(t)[0]
|
| 79 |
+
rows.append({
|
| 80 |
+
"text": t,
|
| 81 |
+
"label": res["label"],
|
| 82 |
+
"score": round(float(res["score"]), 3)
|
| 83 |
+
})
|
| 84 |
+
|
| 85 |
+
return pd.DataFrame(rows)
|
| 86 |
+
|
| 87 |
|
| 88 |
with gr.Blocks() as demo:
|
| 89 |
+
gr.Markdown("🧠 Sentiment Analysis")
|
| 90 |
|
| 91 |
+
with gr.Row():
|
| 92 |
+
text_input = gr.Textbox(label="Введите текст", lines=5)
|
| 93 |
+
model_choice = gr.Dropdown(list(MODELS.keys()), value="Русский (rubert-tiny)", label="Модель")
|
| 94 |
|
| 95 |
+
btn = gr.Button("Обработать")
|
| 96 |
|
| 97 |
+
with gr.Row():
|
| 98 |
+
lab = gr.Textbox(label="Тональность")
|
| 99 |
+
scr = gr.Textbox(label="Уверенность")
|
| 100 |
+
lat = gr.Textbox(label="Время ответа (сек)")
|
| 101 |
|
| 102 |
state = gr.State([])
|
| 103 |
box = gr.Textbox(label="История запросов (последние 5)", lines=5)
|
| 104 |
|
| 105 |
btn.click(
|
| 106 |
analyze_text,
|
| 107 |
+
inputs=[text_input, model_choice, state],
|
| 108 |
+
outputs=[lab, scr, lat, state]
|
| 109 |
).then(
|
| 110 |
lambda h: "\n".join(h),
|
| 111 |
+
inputs=state,
|
| 112 |
+
outputs=box
|
| 113 |
)
|
| 114 |
|
| 115 |
gr.Markdown("# Пакетная обработка (TXT/CSV)")
|
| 116 |
+
file_in = gr.File(label="Загрузите файл (.txt или .csv)")
|
| 117 |
bbtn = gr.Button("Обработать файл")
|
| 118 |
+
obtn = gr.Dataframe(label="Результаты")
|
| 119 |
|
| 120 |
bbtn.click(obr_file, inputs=[file_in, model_choice], outputs=obtn)
|
| 121 |
+
|
| 122 |
gr.Examples(
|
| 123 |
examples=[
|
| 124 |
["Мне очень понравился этот фильм, всё отлично!", "Русский (rubert-tiny)"],
|
| 125 |
["Это худший опыт в моей жизни.", "Русский (rubert-tiny)"],
|
| 126 |
+
["The app is amazing!", "Twitter-roBERTa"],
|
| 127 |
+
["This is terrible and buggy.", "Twitter-roBERTa"]
|
| 128 |
],
|
| 129 |
inputs=[text_input, model_choice],
|
| 130 |
label="Примеры"
|
| 131 |
)
|
| 132 |
|
| 133 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|