Update app.py
Browse files48 unmodified lines495051525354554 unmodified lines6061626364656667686970717273747576776 unmodified lines8485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916084 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892906 unmodified lines297298299300301302303304305158 unmodified lines46446546646746846947058 unmodified lines5295305315325335345357 unmodified lines54354454554654754854955055122 unmodified lines57457557657748 unmodified linesdef associate_speakers_with_timestamps(transcription_result, diarization, tolerance=0.02, min_segment_duration=0.05, max_words_to_merge=20):word_segments = transcription_result['chunks']diarization_segments = list(diarization.itertracks(yield_label=True))speaker_transcription = []4 unmodified linesdef flush_current_segment():nonlocal current_speaker, current_textif current_speaker and current_text:speaker_transcription.append({"speaker": current_speaker,"text": ' '.join(current_text),"start": word_segments[len(speaker_transcription)]['timestamp'][0],"end": word_segments[len(speaker_transcription) + len(current_text) - 1]['timestamp'][1]})current_text = []for word in word_segments:word_start, word_end = word['timestamp']word_text = word['text']matching_segment = Nonefor segment, _, speaker in diarization_segments:if segment.start - tolerance <= word_start < segment.end + tolerance:6 unmodified linesflush_current_segment()current_speaker = speakerif word_start - last_word_end > 1.0: # Pause de plus d'une secondeflush_current_segment()current_text.append(word_text)last_word_end = word_endelse:if current_speaker:current_text.append(word_text)else:current_speaker = "SPEAKER_UNKNOWN"current_text.append(word_text)flush_current_segment()def detect_interruptions(transcription, time_threshold=0.5):for i in range(len(transcription) - 1):current_end = transcription[i]['end']next_start = transcription[i+1]['start']if next_start - current_end < time_threshold:transcription[i]['text'] += ' [...]'transcription[i+1]['text'] = '[...] ' + transcription[i+1]['text']return transcriptionspeaker_transcription = detect_interruptions(speaker_transcription)def post_process_transcription(transcription, max_words):processed = []current_speaker = Nonecurrent_text = []current_start = Nonecurrent_end = Nonefor segment in transcription:if segment['speaker'] == current_speaker and len(' '.join(current_text + [segment['text']]).split()) <= max_words:current_text.append(segment['text'])current_end = segment['end']else:if current_speaker:processed.append({"speaker": current_speaker,"text": ' '.join(current_text),"start": current_start,"end": current_end})current_speaker = segment['speaker']current_text = [segment['text']]current_start = segment['start']current_end = segment['end']if current_speaker:processed.append({"speaker": current_speaker,"text": ' '.join(current_text),"start": current_start,"end": current_end})return processedmerged_transcription = post_process_transcription(speaker_transcription, max_words_to_merge)speakers = sorted(set(segment['speaker'] for segment in merged_transcription))metadata = {"speaker_count": len(speakers),"speakers": speakers}return {"transcription": merged_transcription,"metadata": metadata}def simplify_diarization_output(speaker_transcription):simplified = []84 unmodified linesprogress(1.0, desc="Terminé!")return "Transcription terminée!", transcription_result['text'], speaker_transcriptiondef format_to_markdown(transcription_result, audio_duration=None, location=None, speaker_age=None, context=None, custom_speaker_names=None):if isinstance(transcription_result, dict):metadata = transcription_result.get("metadata", {})transcription = transcription_result.get("transcription", [])else:metadata = {}transcription = transcription_resultspeaker_count = metadata.get("speaker_count", "non spécifié")speakers = metadata.get("speakers", [])metadata_text = "\n".join([f"- **Date de traitement** : '{datetime.now().strftime('%d/%m/%Y %H:%M')}'",f"- **Durée de l'audio** : '{audio_duration if audio_duration else '[à remplir]'} secondes'",f"- **Lieu** : '{location if location else '[non spécifié]'}'",f"- **Âge de l'intervenant** : '{f'{speaker_age} ans' if speaker_age else '[non spécifié]'}'",f"- **Contexte** : '{context if context else '[non spécifié]'}'",f"- **Nombre d'interlocuteurs** : '{speaker_count}'",f"- **Interlocuteurs bruts** : '{', '.join(speakers)}'"])try:formatted_transcription = []for segment in transcription:speaker = segment['speaker']text = segment['text']start_time = format_time(segment['start'])end_time = format_time(segment['end'])if custom_speaker_names and speaker in custom_speaker_names:display_speaker = custom_speaker_names[speaker]else:display_speaker = speakerformatted_transcription.append(f"**[{start_time} - {end_time}] {display_speaker}**: {text}")transcription_text = "\n\n".join(formatted_transcription)except Exception as e:print(f"Error formatting speaker transcription: {e}")transcription_text = "Error formatting speaker transcription. Using raw transcription instead.\n\n" + str(transcription)formatted_output = f"""# Transcription Formatée6 unmodified lines"""return formatted_outputdef format_time(seconds):return f"{int(seconds // 60):02d}:{int(seconds % 60):02d}"def _return_yt_html_embed(yt_url):video_id = yt_url.split("?v=")[-1]HTML_str = (158 unmodified linesaudio_duration = gr.Textbox(label="⏱️ Durée de l'audio (mm:ss)")location = gr.Textbox(label="📍 Lieu de l'enregistrement")speaker_age = gr.Number(label="👤 Âge de l'intervenant principal")custom_speaker_names = gr.TextArea(label="Noms personnalisés des locuteurs (format: SPEAKER_00: Nom1, SPEAKER_01: Nom2)")context = gr.Textbox(label="📝 Contexte de l'enregistrement")format_button = gr.Button("✨ Générer la transcription formatée", elem_classes="button-secondary")58 unmodified lines- Modèles :- [Whisper-médium](https://huggingface.co/openai/whisper-medium) : Model size - 764M params - Tensor type F32 -- [speaker-diarization-3.1](https://huggingface.co/pyannote/speaker-diarization-3.1) : Model size - Unknow - Tensor type F32 -- Version : V.2.0.0-Bêta- Langues : FR, EN- Copyright : cc-by-nc-4.0- [En savoir +](https://huggingface.co/spaces/Woziii/scribe/blob/main/README.md)7 unmodified lines)format_button.click(format_to_markdown,inputs=[raw_output, speaker_output, audio_duration, location, speaker_age, context, custom_speaker_names],outputs=formatted_output)mic_transcribe_button.click(22 unmodified linesif __name__ == "__main__":demo.queue().launch()48 unmodified lines495051525354554 unmodified lines60616263646566676869707172736 unmodified lines808182838485868788899091929394959697989910010110210310410510610710810911011184 unmodified lines1961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252266 unmodified lines233234235236237238158 unmodified lines39739839940040140258 unmodified lines4614624634644654664677 unmodified lines47547647747847948048148248322 unmodified lines50650750850948 unmodified linesdef associate_speakers_with_timestamps(transcription_result, diarization, tolerance=0.02, min_segment_duration=0.05):word_segments = transcription_result['chunks']diarization_segments = list(diarization.itertracks(yield_label=True))speaker_transcription = []4 unmodified linesdef flush_current_segment():nonlocal current_speaker, current_textif current_speaker and current_text:speaker_transcription.append((current_speaker, ' '.join(current_text)))current_text = []for word in word_segments:word_start, word_end = word['timestamp']word_text = word['text']# Trouver le segment de diarisation correspondantmatching_segment = Nonefor segment, _, speaker in diarization_segments:if segment.start - tolerance <= word_start < segment.end + tolerance:6 unmodified linesflush_current_segment()current_speaker = speaker# Gérer les pauses longuesif word_start - last_word_end > 1.0: # Pause de plus d'une secondeflush_current_segment()current_text.append(word_text)last_word_end = word_endelse:# Si aucun segment ne correspond, attribuer au dernier locuteur connuif current_speaker:current_text.append(word_text)else:# Si c'est le premier mot sans correspondance, créer un nouveau segmentcurrent_speaker = "SPEAKER_UNKNOWN"current_text.append(word_text)flush_current_segment()# Fusionner les segments courts du même locuteurmerged_transcription = []for speaker, text in speaker_transcription:if not merged_transcription or merged_transcription[-1][0] != speaker or len(text.split()) > 3:merged_transcription.append((speaker, text))else:merged_transcription[-1] = (speaker, merged_transcription[-1][1] + " " + text)return merged_transcriptiondef simplify_diarization_output(speaker_transcription):simplified = []84 unmodified linesprogress(1.0, desc="Terminé!")return "Transcription terminée!", transcription_result['text'], speaker_transcriptiondef format_to_markdown(transcription_text, speaker_transcription, audio_duration=None, location=None, speaker_age=None, context=None):metadata = {"Date de traitement": datetime.now().strftime('%d/%m/%Y %H:%M'),"Durée de l'audio": f"{audio_duration} secondes" if audio_duration else "[à remplir]","Lieu": location if location else "[non spécifié]","Âge de l'intervenant": f"{speaker_age} ans" if speaker_age else "[non spécifié]","Contexte": context if context else "[non spécifié]"}metadata_text = "\n".join([f"- **{key}** : '{value}'" for key, value in metadata.items()])try:if isinstance(speaker_transcription, str):speaker_transcription = parse_simplified_diarization(speaker_transcription)if isinstance(speaker_transcription, list) and all(isinstance(item, tuple) and len(item) == 2 for item in speaker_transcription):formatted_transcription = []for speaker, text in speaker_transcription:formatted_transcription.append(f"**{speaker}**: {text}")transcription_text = "\n\n".join(formatted_transcription)else:raise ValueError("Invalid speaker transcription format")except Exception as e:print(f"Error formatting speaker transcription: {e}")transcription_text = "Error formatting speaker transcription. Using raw transcription instead.\n\n" + transcription_textformatted_output = f"""# Transcription Formatée6 unmodified lines"""return formatted_outputdef _return_yt_html_embed(yt_url):video_id = yt_url.split("?v=")[-1]HTML_str = (158 unmodified linesaudio_duration = gr.Textbox(label="⏱️ Durée de l'audio (mm:ss)")location = gr.Textbox(label="📍 Lieu de l'enregistrement")speaker_age = gr.Number(label="👤 Âge de l'intervenant principal")context = gr.Textbox(label="📝 Contexte de l'enregistrement")format_button = gr.Button("✨ Générer la transcription formatée", elem_classes="button-secondary")58 unmodified lines- Modèles :- [Whisper-médium](https://huggingface.co/openai/whisper-medium) : Model size - 764M params - Tensor type F32 -- [speaker-diarization-3.1](https://huggingface.co/pyannote/speaker-diarization-3.1) : Model size - Unknow - Tensor type F32 -- Version : V.2.0.2-Bêta- Langues : FR, EN- Copyright : cc-by-nc-4.0- [En savoir +](https://huggingface.co/spaces/Woziii/scribe/blob/main/README.md)7 unmodified lines)format_button.click(format_to_markdown,inputs=[raw_output, speaker_output, audio_duration, location, speaker_age, context],outputs=formatted_output)mic_transcribe_button.click(22 unmodified linesif __name__ == "__main__":demo.queue().launch()
app.py+41-109