LivanArzuaga commited on
Commit
4e360d8
·
verified ·
1 Parent(s): 87ecb50

Update utils_hf.py

Browse files
Files changed (1) hide show
  1. utils_hf.py +92 -15
utils_hf.py CHANGED
@@ -1,23 +1,26 @@
1
  # import numpy as np
2
  # import soundfile as sf
3
  # import torchaudio
 
4
 
5
  import os
6
  import yt_dlp
7
  import streamlit as st
8
  import torch
9
  import whisper
 
10
  from pyannote.audio import Pipeline
11
  from pyannote.audio.pipelines.utils.hook import ProgressHook
12
  from moviepy.editor import AudioFileClip
13
- from transformers import pipeline
14
  from openai import Client
15
  from dotenv import load_dotenv
16
 
17
  load_dotenv()
18
 
19
  hf_token = os.environ.get("HF_DIARIZATION_TOKEN")
20
- api_key = os.environ.get("OPENAI_API_KEY")
 
 
21
 
22
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
  st.info(f"Usando dispositivo: {device}")
@@ -30,12 +33,6 @@ pyannote_pipeline = Pipeline.from_pretrained(
30
  if torch.cuda.is_available():
31
  pyannote_pipeline.to(torch.device("cuda"))
32
 
33
- sumamry_pipeline = pipeline(
34
- "text-generation",
35
- model="gpt2",
36
- device=device,
37
- )
38
-
39
  whisper_model = whisper.load_model("turbo")
40
 
41
 
@@ -84,18 +81,33 @@ def process_transcripts(diarization_text, speakers):
84
 
85
 
86
  def summarize_speaker_transcripts(speaker_transcripts):
87
- summaries = {}
 
 
88
  for speaker, transcripts in speaker_transcripts.items():
89
  full_text = ' '.join(transcripts)
90
  max_tokens = 1024 # Ajusta según el modelo y tus necesidades
91
  if len(full_text) > max_tokens:
92
  full_text = full_text[:max_tokens]
93
 
94
- prompt = f"Por favor, resume el siguiente texto:\n\n{full_text}"
 
 
 
 
95
 
96
- summary = sumamry_pipeline(prompt, max_length=150, min_length=30, do_sample=False)[0]['generated_text']
97
- summaries[speaker] = summary
98
- return summaries
 
 
 
 
 
 
 
 
 
99
 
100
 
101
  def diarize_full_audio(audio_path):
@@ -142,8 +154,7 @@ def extract_audio_segment(input_audio_path, output_audio_path, start_time, end_t
142
 
143
  def transcribe_audio_whisper_lib(audio_path):
144
  try:
145
- with open(audio_path, "rb") as audio_file:
146
- transcript = whisper_model.transcribe(audio_path)
147
  return transcript["text"]
148
  except Exception as e:
149
  st.error(f"Error al transcribir el audio: {e}")
@@ -241,3 +252,69 @@ class StreamlitProgressHook(ProgressHook):
241
  else:
242
  progress_message = f"{step_name:<20} ━ Progress data unavailable"
243
  self.progress_text.text(progress_message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # import numpy as np
2
  # import soundfile as sf
3
  # import torchaudio
4
+ # from transformers import pipeline
5
 
6
  import os
7
  import yt_dlp
8
  import streamlit as st
9
  import torch
10
  import whisper
11
+ import requests
12
  from pyannote.audio import Pipeline
13
  from pyannote.audio.pipelines.utils.hook import ProgressHook
14
  from moviepy.editor import AudioFileClip
 
15
  from openai import Client
16
  from dotenv import load_dotenv
17
 
18
  load_dotenv()
19
 
20
  hf_token = os.environ.get("HF_DIARIZATION_TOKEN")
21
+ oapi_key = os.environ.get("OPENAI_API_KEY")
22
+
23
+ client = Client(api_key=oapi_key)
24
 
25
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
26
  st.info(f"Usando dispositivo: {device}")
 
33
  if torch.cuda.is_available():
34
  pyannote_pipeline.to(torch.device("cuda"))
35
 
 
 
 
 
 
 
36
  whisper_model = whisper.load_model("turbo")
37
 
38
 
 
81
 
82
 
83
  def summarize_speaker_transcripts(speaker_transcripts):
84
+ url = "https://api.gemini.com/v1/generateContent"
85
+ api_key = os.environ.get("GEMINI_API_KEY")
86
+
87
  for speaker, transcripts in speaker_transcripts.items():
88
  full_text = ' '.join(transcripts)
89
  max_tokens = 1024 # Ajusta según el modelo y tus necesidades
90
  if len(full_text) > max_tokens:
91
  full_text = full_text[:max_tokens]
92
 
93
+ data = {
94
+ "prompt": f"Por favor, resume el siguiente texto:\n\n{full_text}",
95
+ "model": "gemini-1.5-pro",
96
+ "max_tokens": 150
97
+ }
98
 
99
+ headers = {
100
+ "Authorization": f"Bearer {api_key}",
101
+ "Content-Type": "application/json"
102
+ }
103
+
104
+ response = requests.post(url, json=data, headers=headers)
105
+
106
+ if response.status_code == 200:
107
+ result = response.json()
108
+ return result["text"]
109
+ else:
110
+ st.error(f"{response.status_code}, {response.text}")
111
 
112
 
113
  def diarize_full_audio(audio_path):
 
154
 
155
  def transcribe_audio_whisper_lib(audio_path):
156
  try:
157
+ transcript = whisper_model.transcribe(audio_path)
 
158
  return transcript["text"]
159
  except Exception as e:
160
  st.error(f"Error al transcribir el audio: {e}")
 
252
  else:
253
  progress_message = f"{step_name:<20} ━ Progress data unavailable"
254
  self.progress_text.text(progress_message)
255
+
256
+ # def diarize_in_segments(audio_path, segment_duration=300):
257
+ # try:
258
+ # audio_duration = get_audio_duration(audio_path)
259
+ # diarization_segments = []
260
+ # diarization_text = ""
261
+ # speakers = set()
262
+ #
263
+ # # Procesar cada segmento por separado
264
+ # for start_time in range(0, int(audio_duration), segment_duration):
265
+ # end_time = min(start_time + segment_duration, audio_duration)
266
+ # st.info(f"Procesando segmento desde {start_time} hasta {end_time} segundos...")
267
+ #
268
+ # with StreamlitProgressHook() as hook:
269
+ # diarization = pyannote_pipeline({
270
+ # 'audio': audio_path,
271
+ # 'start': start_time,
272
+ # 'end': end_time
273
+ # }, hook=hook)
274
+ #
275
+ # for segment, _, speaker in diarization.itertracks(yield_label=True):
276
+ # diarization_segments.append((segment.start, segment.end, speaker))
277
+ # diarization_text += f"{segment.start:.2f} - {segment.end:.2f}: {speaker}\n"
278
+ # speakers.add(speaker)
279
+ #
280
+ # return diarization_segments, diarization_text, speakers
281
+ # except Exception as e:
282
+ # st.error(f"Error al realizar la diarización de un segmento: {e}")
283
+ # return None, None, 0
284
+
285
+ # def transcribe_audio_whisper_transformers(audio_path):
286
+ # try:
287
+ # # Leer el archivo de audio y convertirlo en un numpy ndarray
288
+ # audio_data, _ = sf.read(audio_path)
289
+ #
290
+ # # Convertir a un solo canal si es necesario
291
+ # if len(audio_data.shape) > 1:
292
+ # audio_data = np.mean(audio_data, axis=1)
293
+ #
294
+ # # Transcribir el audio usando el modelo Whisper
295
+ # transcript = whisper_pipeline(audio_data, return_timestamps=True)
296
+ # return transcript['text']
297
+ # except Exception as e:
298
+ # st.error(f"Error al transcribir el audio: {e}")
299
+ # st.stop()
300
+
301
+
302
+ # sumamry_pipeline = pipeline(
303
+ # "text-generation",
304
+ # model="gpt2",
305
+ # device=device,
306
+ # )
307
+
308
+ # def summarize_speaker_transcripts_gpt2(speaker_transcripts):
309
+ # summaries = {}
310
+ # for speaker, transcripts in speaker_transcripts.items():
311
+ # full_text = ' '.join(transcripts)
312
+ # max_tokens = 1024 # Ajusta según el modelo y tus necesidades
313
+ # if len(full_text) > max_tokens:
314
+ # full_text = full_text[:max_tokens]
315
+ #
316
+ # prompt = f"Por favor, resume el siguiente texto:\n\n{full_text}"
317
+ #
318
+ # summary = sumamry_pipeline(prompt, max_length=150, min_length=30, do_sample=False)[0]['generated_text']
319
+ # summaries[speaker] = summary
320
+ # return summaries