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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -36
app.py CHANGED
@@ -1,18 +1,16 @@
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
  )
18
 
@@ -31,48 +29,35 @@ classifier = pipeline(
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
 
1
  import gradio as gr
2
  from transformers import pipeline, AutoTokenizer
3
  import torch
4
+ from transformers.pipelines.audio_utils import ffmpeg_read
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 para transcrição de áudio
10
  transcriber = pipeline(
11
  task="automatic-speech-recognition",
12
+ model="openai/whisper-medium", # Você pode alterar para 'openai/whisper-small' para maior velocidade
13
  device=device,
 
 
14
  generate_kwargs={"language": "Portuguese", "task": "transcribe"}
15
  )
16
 
 
29
  )
30
 
31
  def transcribe_and_analyze(audio_file):
32
+ progress = gr.Progress(track_tqdm=True)
33
+ progress(0, desc="Iniciando transcrição...")
34
+
35
+ # Lendo o arquivo de áudio
36
+ audio_data = ffmpeg_read(audio_file, sampling_rate=16000)
37
+
38
+ # Transcrevendo o áudio
39
+ transcription_result = transcriber(audio_data, sampling_rate=16000)
40
+ transcription = transcription_result["text"]
41
+ progress(50, desc="Transcrição concluída. Analisando emoções...")
42
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  # Lista de emoções para a classificação
44
  emotions = ["alegria", "tristeza", "raiva", "nojo", "medo", "ansiedade", "vergonha", "tédio", "inveja"]
45
+
46
  # Realizando a classificação zero-shot na transcrição
47
  classification = classifier(transcription, emotions, multi_label=True)
48
+
49
  # Formatando os resultados
50
  results = []
51
  for label, score in zip(classification["labels"], classification["scores"]):
52
  results.append(f"{label.capitalize()}: {score:.2f}")
53
+
54
  # Ordenando os resultados por score decrescente
55
  results.sort(key=lambda x: float(x.split(": ")[1]), reverse=True)
56
+
57
  emotion_output = "\n".join(results)
58
+
59
+ progress(100, desc="Processamento concluído.")
60
+
61
  yield transcription, emotion_output
62
 
63
  # Criando a interface Gradio com barra de progresso