File size: 4,436 Bytes
cf6ce9f bad5c84 c945b9f c887c55 844ccec 740442f a463449 9812b5d 740442f 9812b5d 740442f c887c55 844ccec c887c55 bad5c84 c887c55 bad5c84 3be443b c887c55 34fc453 bad5c84 34fc453 bad5c84 34fc453 c887c55 bad5c84 844ccec bad5c84 844ccec bad5c84 844ccec bad5c84 844ccec bad5c84 844ccec bad5c84 844ccec bad5c84 844ccec bad5c84 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
import os
import gradio as gr
import replicate
from pydub import AudioSegment
from fpdf import FPDF
# Aseg煤rate de que REPLICATE_API_TOKEN est茅 configurado en las variables de entorno
replicate_token = os.getenv("REPLICATE_API_TOKEN")
if not replicate_token:
raise ValueError("No se ha encontrado el token de API de Replicate.")
# Funci贸n para dividir el archivo de audio en segmentos de duraci贸n definida (en milisegundos)
def dividir_audio(audio_path, segment_duration_ms=5*60*1000):
audio = AudioSegment.from_file(audio_path)
audio_length = len(audio)
segments = []
# Divide el audio en fragmentos de la duraci贸n especificada
for i in range(0, audio_length, segment_duration_ms):
segment = audio[i:i + segment_duration_ms] # Cada fragmento de hasta la duraci贸n especificada
segment_path = f"segment_{i // (60 * 1000)}.wav" # Nombre del archivo con el 铆ndice del minuto
segment.export(segment_path, format="wav") # Exporta el fragmento como un archivo WAV
# Verifica el tama帽o del archivo y asegura que no supere el l铆mite de 10MB
if os.path.getsize(segment_path) > 10 * 1024 * 1024: # 10 MB
print(f"Warning: Segment {segment_path} exceeds 10MB, reducing segment duration.")
return dividir_audio(audio_path, segment_duration_ms // 2) # Recursivamente reduce el tama帽o del segmento
segments.append(segment_path)
return segments
# Funci贸n para crear el PDF
def crear_pdf(transcripcion):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
# Agregar la transcripci贸n al PDF l铆nea por l铆nea
for line in transcripcion.split("\n"):
pdf.multi_cell(0, 10, line)
# Guardar el archivo PDF en la carpeta actual
pdf_path = "/mnt/data/transcripcion_audio.pdf"
pdf.output(pdf_path)
return pdf_path
# Funci贸n para transcribir los segmentos de audio y generar el PDF
def transcribe_audio_y_pdf(audio_file, progress=gr.Progress()):
# Cargar el archivo de audio completo
audio = AudioSegment.from_file(audio_file)
audio_duration_minutes = len(audio) / (1000 * 60) # Duraci贸n en minutos
# Si el audio dura m谩s de 5 minutos, dividirlo en segmentos de 5 minutos
if audio_duration_minutes > 5:
segments = dividir_audio(audio_file, segment_duration_ms=5 * 60 * 1000) # 5 minutos en milisegundos
else:
segments = [audio_file] # Si es menor de 5 minutos, no dividir
# Almacenar todas las transcripciones
all_transcriptions = []
# Procesar cada segmento individualmente y mostrar progresivamente
for index, segment_path in enumerate(segments):
with open(segment_path, "rb") as audio:
try:
progress(index / len(segments)) # Actualizar el progreso
output = replicate.run(
"vaibhavs10/incredibly-fast-whisper:3ab86df6c8f54c11309d4d1f930ac292bad43ace52d10c80d87eb258b3c9f79c",
input={
"task": "transcribe",
"audio": audio, # El archivo de audio cargado
"language": "None", # Detecta autom谩ticamente el idioma
"timestamp": "chunk", # Incluye marcas de tiempo
"batch_size": 64,
"diarise_audio": False
}
)
transcription = output['text']
all_transcriptions.append(f"Segment {index + 1}:\n{transcription}")
except Exception as e:
return f"Error transcribiendo el segmento {index + 1}: {e}"
# Combina todas las transcripciones en una sola cadena
full_transcription = "\n".join(all_transcriptions)
# Crear PDF y devolver la ruta del archivo
pdf_path = crear_pdf(full_transcription)
return full_transcription, pdf_path
# Crea la interfaz de Gradio
with gr.Blocks() as demo:
gr.Markdown("# Transcriptor de Audio a Texto (Genera PDF)")
audio_input = gr.Audio(type="filepath", label="Sube tu archivo de audio")
output_text = gr.Textbox(label="Transcripci贸n")
output_pdf = gr.File(label="Descarga el PDF")
transcribe_button = gr.Button("Transcribir y Crear PDF")
transcribe_button.click(fn=transcribe_audio_y_pdf, inputs=audio_input, outputs=[output_text, output_pdf])
# Ejecuta la aplicaci贸n
demo.launch()
|