Artemyr commited on
Commit
9e200c5
·
verified ·
1 Parent(s): aa5d4b8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -83
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
- if key not in _pipes:
20
- _pipes[key] = pipeline("sentiment-analysis", model=MODELS[key])
21
- #анализ текста с историей
22
- def analyze_text(text,model_key, history):
23
- start = time.time()
24
-
25
- if text is None or not text.strip():
26
- return "Ошибка пустой ввод", "", 0.0, history
27
-
28
- text = text.strip()
29
- if len(text) > MAX_CHARS:
30
- return "Ошибка: текст слишком длинный", "", 0.0, history
31
-
32
- try:
33
- a = get_pipe(model_key)
34
- res = a(text)[0]
35
- label = res["label"]
36
- score = round(float(res["score"]),3)
37
- except Exception as e:
38
- return f"Ошибка модели: {e}", "", 0.0, history
39
-
40
- latency = round(time.time()- start,3)
41
- record = f"[{model_key}] {text[:80]}... → {label} ({score}), {latency}s"
42
- if not history:
43
- history = []
44
- history = history[-(History_size-1):]
45
- history.append(record)
46
-
47
- return label, score, latency, history
48
-
49
- #функция для обработки файла
 
 
 
 
 
50
  def obr_file(file_obj, model_key):
51
- if file_obj is None:
52
- return pd.DataFrame({"error": ["Файл не загружен"]})
53
- #проверяем расширение файла
54
- path = file_obj.name.lower()
55
- if not (path.endswith(".txt") or path.endswith(".csv")):
56
- return pd.DataFrame({"error": ["Поддерживаются только .txt и .csv"]})
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
- except Exception as e:
68
  return pd.DataFrame({"error": [f"Ошибка чтения файла: {e}"]})
69
-
70
- a = get_pipe(model_key)
71
- rows = []
72
-
73
- for t in texts:
74
- t = t[:MAX_CHARS]
75
- res = a(t)[0]
76
- rows.append({
77
- "text": t,
78
- "label": res["label"],
79
- "score": round(float(res["score"]), 3)
80
- })
81
- return pd.DataFrame(rows)
 
 
82
 
83
  with gr.Blocks() as demo:
84
- gr.Markdown('🧠 Sentiment Analysis')
85
 
86
- with gr.Row():
87
- text_input = gr.Textbox(label='Введите текст', lines =5)
88
- model_choice = gr.Dropdown(list(MODELS.keys()), value="Русский (rubert-tiny)", label="Модель")
89
 
90
- btn = gr.Button("Обработать")
91
 
92
- with gr.Row():
93
- lab = gr.Textbox(label='Тональность')
94
- scr = gr.Textbox(label = 'Уверенность')
95
- lat = gr.Textbox(label = 'Время ответа (сек)')
96
 
97
  state = gr.State([])
98
  box = gr.Textbox(label="История запросов (последние 5)", lines=5)
99
 
100
  btn.click(
101
  analyze_text,
102
- inputs = [text_input, model_choice, state],
103
- outputs = [lab, scr, lat, state]
104
  ).then(
105
  lambda h: "\n".join(h),
106
- inputs = state,
107
- outputs = box
108
  )
109
 
110
  gr.Markdown("# Пакетная обработка (TXT/CSV)")
111
- file_in = gr.File(label = "Загрузите файл (.txt или .csv)")
112
  bbtn = gr.Button("Обработать файл")
113
- obtn = gr.DataFrame(label = 'Результаты')
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!", "Английский (Twitter-roBERTa)"],
121
- ["This is terrible and buggy.", "Английский (Twitter-roBERTa)"]
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()