marioluciofjr commited on
Commit
4ab03ed
·
verified ·
1 Parent(s): 2a78fb3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -21
app.py CHANGED
@@ -1,16 +1,17 @@
1
  import gradio as gr
2
  from transformers import pipeline, AutoTokenizer
3
  import torch
 
4
 
5
  # Verificando se a GPU está disponível
6
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
7
 
8
- # Carregando o modelo Whisper avançado para transcrição de áudio
9
  transcriber = pipeline(
10
  task="automatic-speech-recognition",
11
- model="openai/whisper-medium",
12
  device=device,
13
- chunk_length_s=20,
14
  stride_length_s=5,
15
  generate_kwargs={"language": "Portuguese", "task": "transcribe"}
16
  )
@@ -30,34 +31,49 @@ classifier = pipeline(
30
  )
31
 
32
  def transcribe_and_analyze(audio_file):
33
- progress = gr.Progress(track_tqdm=True)
34
- progress(0, desc="Iniciando transcrição...")
35
-
36
- # Transcrevendo o áudio
37
- transcription_result = transcriber(audio_file)
38
- transcription = transcription_result["text"]
39
- progress(50, desc="Transcrição concluída. Analisando emoções...")
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  # Lista de emoções para a classificação
42
  emotions = ["alegria", "tristeza", "raiva", "nojo", "medo", "ansiedade", "vergonha", "tédio", "inveja"]
43
-
44
- # Realizando a classificação zero-shot
45
  classification = classifier(transcription, emotions, multi_label=True)
46
-
47
  # Formatando os resultados
48
  results = []
49
  for label, score in zip(classification["labels"], classification["scores"]):
50
  results.append(f"{label.capitalize()}: {score:.2f}")
51
-
52
  # Ordenando os resultados por score decrescente
53
  results.sort(key=lambda x: float(x.split(": ")[1]), reverse=True)
54
-
55
- # Unindo os resultados em uma string
56
  emotion_output = "\n".join(results)
57
-
58
- progress(100, desc="Processamento concluído.")
59
-
60
- return transcription, emotion_output
61
 
62
  # Criando a interface Gradio com barra de progresso
63
  interface = gr.Interface(
@@ -68,7 +84,7 @@ interface = gr.Interface(
68
  gr.Textbox(label="Emoções Detectadas")
69
  ],
70
  title="Voxsense 🗣️❣️",
71
- description="Envie um arquivo de áudio de até 1 hora para transcrição e análise de emoções.",
72
  theme="default"
73
  )
74
 
 
1
  import gradio as gr
2
  from transformers import pipeline, AutoTokenizer
3
  import torch
4
+ import time
5
 
6
  # Verificando se a GPU está disponível
7
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
8
 
9
+ # Carregando o modelo Whisper pequeno para transcrição de áudio
10
  transcriber = pipeline(
11
  task="automatic-speech-recognition",
12
+ model="openai/whisper-medium", # Modelo menor para maior velocidade
13
  device=device,
14
+ chunk_length_s=30, # Ajuste conforme necessário
15
  stride_length_s=5,
16
  generate_kwargs={"language": "Portuguese", "task": "transcribe"}
17
  )
 
31
  )
32
 
33
  def transcribe_and_analyze(audio_file):
34
+ import numpy as np
 
 
 
 
 
 
35
 
36
+ # Dividindo o áudio em chunks
37
+ total_duration = transcriber.feature_extractor.sampling_rate * 30 # 30 segundos
38
+ audio_input, _ = transcriber.feature_extractor(audio_file, return_tensors="pt").values()
39
+ audio_length = audio_input.shape[1]
40
+ num_chunks = int(np.ceil(audio_length / total_duration))
41
+
42
+ transcription = ""
43
+
44
+ for i in range(num_chunks):
45
+ start_time = i * total_duration
46
+ end_time = min((i + 1) * total_duration, audio_length)
47
+ chunk = audio_input[:, int(start_time):int(end_time)]
48
+
49
+ # Transcrevendo o chunk
50
+ chunk_transcription = transcriber(chunk, generate_kwargs={"language": "Portuguese", "task": "transcribe"})["text"]
51
+ transcription += chunk_transcription + " "
52
+
53
+ # Atualizando a barra de progresso
54
+ progress = int((i + 1) / num_chunks * 100)
55
+ yield f"Transcrevendo... {progress}% concluído", ""
56
+
57
+ # Após a transcrição completa, analisar as emoções
58
+ yield "Análise de emoções em andamento...", ""
59
+
60
  # Lista de emoções para a classificação
61
  emotions = ["alegria", "tristeza", "raiva", "nojo", "medo", "ansiedade", "vergonha", "tédio", "inveja"]
62
+
63
+ # Realizando a classificação zero-shot na transcrição
64
  classification = classifier(transcription, emotions, multi_label=True)
65
+
66
  # Formatando os resultados
67
  results = []
68
  for label, score in zip(classification["labels"], classification["scores"]):
69
  results.append(f"{label.capitalize()}: {score:.2f}")
70
+
71
  # Ordenando os resultados por score decrescente
72
  results.sort(key=lambda x: float(x.split(": ")[1]), reverse=True)
73
+
 
74
  emotion_output = "\n".join(results)
75
+
76
+ yield transcription, emotion_output
 
 
77
 
78
  # Criando a interface Gradio com barra de progresso
79
  interface = gr.Interface(
 
84
  gr.Textbox(label="Emoções Detectadas")
85
  ],
86
  title="Voxsense 🗣️❣️",
87
+ description="Envie um arquivo de áudio para transcrição e análise de emoções.",
88
  theme="default"
89
  )
90