mechtnet commited on
Commit
f81d1c9
·
verified ·
1 Parent(s): 5ecd43e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -18
app.py CHANGED
@@ -1,4 +1,5 @@
1
  # app.py
 
2
  import gradio as gr
3
  from transformers import pipeline
4
  import json
@@ -6,46 +7,55 @@ import os
6
 
7
  def analyze_lyrics():
8
  try:
9
- # Инициализируем классификатор
10
  classifier = pipeline("sentiment-analysis", model="blanchefort/rubert-base-cased-sentiment")
11
 
12
- # Путь к файлу в пространстве Spaces
13
- # Файл должен находиться в корневой директории вашего Space
14
  file_path = os.path.join(os.getcwd(), "test.txt")
15
 
 
 
 
16
  print(f"Пытаемся прочитать файл: {file_path}")
17
  print(f"Файл существует: {os.path.exists(file_path)}")
18
 
19
  if not os.path.exists(file_path):
20
- return "Файл не найден"
21
-
 
22
  with open(file_path, 'r', encoding='utf-8') as file:
23
  text = file.read()
24
- print(f"Прочитано символов: {len(text)}")
25
-
 
26
  results = []
27
  lines = [line.strip() for line in text.split('\n') if line.strip()]
28
-
29
  for line in lines:
30
  prediction = classifier(line)
31
  results.append({
32
  'text': line,
33
  'emotion': prediction[0]['label'],
34
- 'score': float(prediction[0]['score'])
35
  })
36
-
37
- return json.dumps(results, ensure_ascii=False, indent=2)
38
-
 
 
39
  except Exception as e:
40
- return f"Ошибка: {str(e)}"
 
41
 
42
- # Создаем интерфейс
43
  demo = gr.Interface(
44
  fn=analyze_lyrics,
45
- inputs=None, # Без входных параметров
46
- outputs=gr.JSON(),
47
- title="Анализ эмоций в тексте песни",
48
- description="Нажмите кнопку для анализа файла test.txt"
49
  )
50
 
 
51
  demo.launch()
 
1
  # app.py
2
+
3
  import gradio as gr
4
  from transformers import pipeline
5
  import json
 
7
 
8
  def analyze_lyrics():
9
  try:
10
+ # Инициализируем пайплайн анализа тональности
11
  classifier = pipeline("sentiment-analysis", model="blanchefort/rubert-base-cased-sentiment")
12
 
13
+ # Путь к текстовому файлу с текстом песни
14
+ # Убедитесь, что файл 'test.txt' находится в том же каталоге, что и этот скрипт
15
  file_path = os.path.join(os.getcwd(), "test.txt")
16
 
17
+ # Отладочная информация
18
+ print(f"Текущая рабочая директория: {os.getcwd()}")
19
+ print(f"Содержимое директории: {os.listdir()}")
20
  print(f"Пытаемся прочитать файл: {file_path}")
21
  print(f"Файл существует: {os.path.exists(file_path)}")
22
 
23
  if not os.path.exists(file_path):
24
+ return "Ошибка: Файл 'test.txt' не найден в текущей директории."
25
+
26
+ # Читаем содержимое файла
27
  with open(file_path, 'r', encoding='utf-8') as file:
28
  text = file.read()
29
+ print(f"Количество прочитанных символов: {len(text)}")
30
+
31
+ # Разбиваем текст на строки и анализируем каждую строку
32
  results = []
33
  lines = [line.strip() for line in text.split('\n') if line.strip()]
34
+
35
  for line in lines:
36
  prediction = classifier(line)
37
  results.append({
38
  'text': line,
39
  'emotion': prediction[0]['label'],
40
+ 'score': round(float(prediction[0]['score']), 3)
41
  })
42
+
43
+ # Форматируем результаты в JSON
44
+ formatted_results = json.dumps(results, ensure_ascii=False, indent=2)
45
+ return formatted_results
46
+
47
  except Exception as e:
48
+ # Возвращаем сообщение об ошибке
49
+ return f"Произошла ошибка: {str(e)}"
50
 
51
+ # Создаем интерфейс Gradio
52
  demo = gr.Interface(
53
  fn=analyze_lyrics,
54
+ inputs=None, # Нет входных данных, так как мы читаем из файла
55
+ outputs="text",
56
+ title="Анализ эмоциональной окраски текста песни",
57
+ description="Нажмите кнопку для анализа эмоций в файле 'test.txt'"
58
  )
59
 
60
+ # Запускаем Gradio приложение
61
  demo.launch()