rick commited on
Commit
c21f366
·
unverified ·
1 Parent(s): 30928b9

... not done...

Browse files
Files changed (2) hide show
  1. pages/main.py +202 -188
  2. requirements.txt +2 -2
pages/main.py CHANGED
@@ -19,7 +19,7 @@ from io import BytesIO
19
  # Third-party libraries
20
  import requests
21
  import streamlit as st
22
- from audiorecorder import audiorecorder
23
  from openai import OpenAI
24
  from pydub import AudioSegment
25
  import warnings
@@ -471,6 +471,140 @@ def init_process_mode(
471
 
472
 
473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  def main_page():
475
  """Page principale de l'application."""
476
 
@@ -495,23 +629,79 @@ def main_page():
495
  if "interface_language_select" not in st.session_state:
496
  st.session_state.interface_language_select = "English" # Langue par défaut
497
 
 
 
 
 
 
 
 
 
 
 
 
498
 
499
  # Initialisation de l'historique des messages avec le prompt système
500
  if "messages" not in st.session_state:
501
  st.session_state.messages = []
502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503
  with st.container(border=True):
504
  # Interface utilisateur pour le chat textuel
505
  st.session_state.user_input = st.chat_input(
506
  get_translation("entrez_message")
507
  )
508
- st.session_state.audio = audiorecorder(
509
- start_prompt=get_translation("cliquez_enregistrer"),
510
- stop_prompt=get_translation("cliquez_arreter"),
511
- pause_prompt=get_translation("cliquez_pause"),
512
- show_visualizer=True,
513
- key="vocal_chat_input"
514
- )
 
 
515
 
516
 
517
  if st.session_state.user_input:
@@ -623,122 +813,13 @@ def main_page():
623
  # ##
624
  audio_status.update(label=f"{get_translation('erreur_concatenation_audio')} : {str(e)}", state="error", expanded=True)
625
 
626
- clear_inputs_garbages()
627
  # Interface utilisateur pour l'enregistrement audio
628
  # st.write(f"🗣️ {get_translation('enregistrez_message')}")
629
 
630
 
631
- elif st.session_state.audio:
632
- if "language_detected" not in st.session_state:
633
- st.session_state.language_detected = None
634
-
635
- # Traitement de l'entrée audio de l'utilisateur
636
- if len(st.session_state.audio) > 0:
637
- if st.session_state.audio:
638
- try:
639
- st.subheader(f"Frame rate: {st.session_state.audio.frame_rate}, Frame width: {st.session_state.audio.frame_width}, Duration: {st.session_state.audio.duration_seconds} seconds")
640
-
641
- with tempfile.NamedTemporaryFile(suffix=".mp3", delete_on_close=False) as tmp_file:
642
- st.session_state.audio.export(tmp_file, format="mp3")
643
- tmp_file.close()
644
-
645
- # Transcrire l'audio en texte
646
- st.session_state.transcription = transcribe_audio(
647
- tmp_file,
648
- language=st.session_state.language_detected
649
- )
650
-
651
- st.markdown(
652
- f"🎤 {get_translation('transcription_audio')}".format(
653
- f"{st.session_state.transcription}"
654
- )
655
- )
656
-
657
- # Detecter la langue du texte transcrit (si la langue source n'est pas détectée)
658
- if st.session_state.language_detected is None:
659
- st.session_state.language_detected = detect_language(
660
- input_text=st.session_state.transcription, temperature=0.01
661
- )
662
- st.markdown(
663
- f"- {get_translation('langue_detectee')}".format(
664
- f"{convert_iso6391_to_language_name(st.session_state.language_detected)}"
665
- )
666
- )
667
-
668
-
669
- st.session_state.audio_list = []
670
- for cursor_selected_lang in st.session_state.selected_languages:
671
- st.session_state.target_language = cursor_selected_lang["iso-639-1"]
672
- st.session_state.full_response = ""
673
 
674
- # Initialisation du mode de traitement pour la langue cible actuelle
675
- st.session_state.system_prompt, st.session_state.operation_prompt = init_process_mode(from_lang=
676
- (
677
- st.session_state.language_detected if "language_detected" in st.session_state.language_detected else convert_language_name_to_iso6391(
678
- st.session_state.interface_language
679
- )
680
- ),
681
- to_lang=st.session_state.target_language
682
- )
683
-
684
- with st.chat_message("assistant", avatar="👻"):
685
- message_placeholder = st.empty()
686
- st.session_state.response_generator = process_message(
687
- st.session_state.transcription,
688
- st.session_state.operation_prompt,
689
- st.session_state.enable_tts_for_input_from_audio_record,
690
- st.session_state.system_prompt
691
- )
692
-
693
- for response_chunk in st.session_state.response_generator:
694
- message_placeholder.markdown(response_chunk)
695
- st.session_state.end_response = st.session_state.response_generator.close()
696
- if st.session_state.full_response != "":
697
- message_placeholder.markdown(st.session_state.full_response)
698
-
699
- if st.session_state.enable_tts_for_input_from_audio_record:
700
- st.session_state.tts_audio, st.session_state.tts_duration = process_tts_message(st.session_state.full_response)
701
-
702
- if st.session_state.tts_audio:
703
- st.session_state.audio_list.append(
704
- ( st.session_state.tts_audio,
705
- st.session_state.tts_duration )
706
- )
707
- else:
708
- pass
709
-
710
- if st.session_state.audio_list:
711
- st.session_state.final_audio = concatenate_audio_files(st.session_state.audio_list)
712
-
713
- with st.container(border=True):
714
-
715
- # Générer un nom de fichier unique
716
- st.session_state.timestamp = time.strftime("%Y%m%d-%H%M%S")
717
- st.session_state.langues = "_".join([lang["iso-639-1"] for lang in st.session_state.selected_languages])
718
- st.session_state.nom_fichier = f"reponse_audio_{st.session_state.langues}_{st.session_state.timestamp}.mp3"
719
-
720
- st.audio(st.session_state.final_audio,
721
- format="audio/mp3",
722
- autoplay=st.session_state.autoplay_tts)
723
-
724
- st.download_button(
725
- label=f"📥 {get_translation('telecharger_audio')}",
726
- data=st.session_state.final_audio,
727
- file_name=st.session_state.nom_fichier,
728
- mime="audio/mp3",
729
- use_container_width=True,
730
- type="primary",
731
- key=f"download_button_{st.session_state.langues}_{st.session_state.timestamp}",
732
- )
733
-
734
- except Exception as e:
735
- st.error(f"[AUDIO] - Erreur lors de l'exportation de l'audio : {str(e)}")
736
- finally:
737
- clear_inputs_garbages()
738
- # if 'tmp_file' in locals():
739
- # os.unlink(tmp_file.name)
740
-
741
-
742
 
743
 
744
 
@@ -758,77 +839,10 @@ def clear_inputs_garbages(sessions_state_list: Optional[list] =
758
  delete_session_state_var(it_var_name)
759
 
760
 
761
- clear_inputs_garbages()
762
 
763
- def on_languages_change() -> None:
764
- clear_inputs_garbages()
765
- """Fonction de rappel pour le changement de langue(s) de destination."""
766
- selected_language_names: List[str] = st.session_state.language_selector
767
- st.session_state.selected_languages = [
768
- {"language": lang, "iso-639-1": convert_language_name_to_iso6391(lang)}
769
- for lang in selected_language_names
770
- ]
771
-
772
-
773
-
774
- # Configuration de la barre latérale
775
- with st.sidebar:
776
- st.logo("img/logo_2.png", icon_image="img/logo_2.png")
777
- st.header(get_translation("sidebar_titre"))
778
-
779
- with st.expander(f"{get_translation('a_propos')}",
780
- expanded=False,
781
- icon="ℹ️"):
782
- st.subheader(f"version: {__version__}")
783
- st.info(get_translation("info_app"))
784
-
785
-
786
- with st.expander(f"{get_translation('selection_langue')}",
787
- expanded=True,
788
- icon="🌐"):
789
- # Conteneur pour la sélection de langue
790
-
791
- # Sélection multiple des langues de destination
792
- st.multiselect(
793
- label=get_translation("langues_destination"),
794
- placeholder=get_translation("placeholder_langues"),
795
- options=SUPPORTED_LANGUAGES,
796
- default=["English"],
797
- key="language_selector",
798
- max_selections=4,
799
- on_change=on_languages_change,
800
- format_func=lambda lang: f"{LANGUAGES_EMOJI.get(lang, '')} {lang}"
801
- )
802
-
803
- with st.expander(f"{get_translation('parametres_tts')}",
804
- expanded=True,
805
- icon="🔊"):
806
- st.selectbox(
807
- get_translation("choix_voix_tts"),
808
- options=["alloy", "echo", "fable", "onyx", "nova", "shimmer"],
809
- index=3, # "onyx" est à l'index 3
810
- key="tts_voice",
811
- on_change=clear_inputs_garbages
812
- )
813
- st.checkbox(
814
- get_translation("activer_tts_texte"),
815
- key="enable_tts_for_input_from_text_field",
816
- value=True,
817
- on_change=clear_inputs_garbages
818
- )
819
- st.checkbox(
820
- get_translation("activer_tts_audio"),
821
- key="enable_tts_for_input_from_audio_record",
822
- value=True,
823
- on_change=clear_inputs_garbages
824
- )
825
- st.checkbox(
826
- get_translation("lecture_auto_tts"),
827
- key="autoplay_tts",
828
- value=True,
829
- on_change=clear_inputs_garbages
830
- )
831
 
832
 
833
 
834
  main_page()
 
 
19
  # Third-party libraries
20
  import requests
21
  import streamlit as st
22
+ #from audiorecorder import audiorecorder
23
  from openai import OpenAI
24
  from pydub import AudioSegment
25
  import warnings
 
471
 
472
 
473
 
474
+
475
+ @st.dialog("Settings")
476
+ def vote(item):
477
+ st.write(f"Why is {item} your favorite?")
478
+ reason = st.text_input("Because...")
479
+ if st.button("Submit"):
480
+ st.session_state.vote = {"item": item, "reason": reason}
481
+ st.rerun()
482
+
483
+
484
+ @st.fragment
485
+ def recorder_released():
486
+ if "rec_widget" in st.session_state:
487
+ if st.session_state.rec_widget:
488
+ audio_recorded = True
489
+ else:
490
+ audio_recorded = False
491
+
492
+ if audio_recorded:
493
+ audio = AudioSegment.from_wav(io.BytesIO(st.session_state.rec_widget.getvalue()))
494
+ st.write(f"Frame rate: {audio.frame_rate}, Frame width: {audio.frame_width}, Duration: {audio.duration_seconds} seconds")
495
+
496
+ try:
497
+
498
+
499
+ with tempfile.NamedTemporaryFile(suffix=".mp3", delete_on_close=False) as tmp_file:
500
+ audio.export(tmp_file, format="mp3")
501
+ tmp_file.close()
502
+
503
+ # Transcrire l'audio en texte
504
+ st.session_state.transcription = transcribe_audio(
505
+ tmp_file,
506
+ language=st.session_state.language_detected
507
+ )
508
+ audio = AudioSegment.empty()
509
+
510
+ st.markdown(
511
+ f"🎤 {get_translation('transcription_audio')}".format(
512
+ f"{st.session_state.transcription}"
513
+ )
514
+ )
515
+
516
+ # Detecter la langue du texte transcrit (si la langue source n'est pas détectée)
517
+ if st.session_state.language_detected is None:
518
+ st.session_state.language_detected = detect_language(
519
+ input_text=st.session_state.transcription, temperature=0.01
520
+ )
521
+ st.markdown(
522
+ f"- {get_translation('langue_detectee')}".format(
523
+ f"{convert_iso6391_to_language_name(st.session_state.language_detected)}"
524
+ )
525
+ )
526
+
527
+
528
+ st.session_state.audio_list = []
529
+ for cursor_selected_lang in st.session_state.selected_languages:
530
+ st.session_state.target_language = cursor_selected_lang["iso-639-1"]
531
+ st.session_state.full_response = ""
532
+
533
+ # Initialisation du mode de traitement pour la langue cible actuelle
534
+ st.session_state.system_prompt, st.session_state.operation_prompt = init_process_mode(from_lang=
535
+ (
536
+ st.session_state.language_detected if "language_detected" in st.session_state.language_detected else convert_language_name_to_iso6391(
537
+ st.session_state.interface_language
538
+ )
539
+ ),
540
+ to_lang=st.session_state.target_language
541
+ )
542
+
543
+ with st.chat_message("assistant", avatar="👻"):
544
+ message_placeholder = st.empty()
545
+ st.session_state.response_generator = process_message(
546
+ st.session_state.transcription,
547
+ st.session_state.operation_prompt,
548
+ st.session_state.enable_tts_for_input_from_audio_record,
549
+ st.session_state.system_prompt
550
+ )
551
+
552
+ for response_chunk in st.session_state.response_generator:
553
+ message_placeholder.markdown(response_chunk)
554
+ st.session_state.end_response = st.session_state.response_generator.close()
555
+ if st.session_state.full_response != "":
556
+ message_placeholder.markdown(st.session_state.full_response)
557
+
558
+ if st.session_state.enable_tts_for_input_from_audio_record:
559
+ st.session_state.tts_audio, st.session_state.tts_duration = process_tts_message(st.session_state.full_response)
560
+
561
+ if st.session_state.tts_audio:
562
+ st.session_state.audio_list.append(
563
+ ( st.session_state.tts_audio,
564
+ st.session_state.tts_duration )
565
+ )
566
+ else:
567
+ pass
568
+
569
+ if st.session_state.audio_list:
570
+ st.session_state.final_audio = concatenate_audio_files(st.session_state.audio_list)
571
+
572
+ with st.container(border=True):
573
+
574
+ # Générer un nom de fichier unique
575
+ st.session_state.timestamp = time.strftime("%Y%m%d-%H%M%S")
576
+ st.session_state.langues = "_".join([lang["iso-639-1"] for lang in st.session_state.selected_languages])
577
+ st.session_state.nom_fichier = f"reponse_audio_{st.session_state.langues}_{st.session_state.timestamp}.mp3"
578
+
579
+ st.audio(st.session_state.final_audio,
580
+ format="audio/mp3",
581
+ autoplay=st.session_state.autoplay_tts)
582
+
583
+ st.download_button(
584
+ label=f"📥 {get_translation('telecharger_audio')}",
585
+ data=st.session_state.final_audio,
586
+ file_name=st.session_state.nom_fichier,
587
+ mime="audio/mp3",
588
+ use_container_width=True,
589
+ type="primary",
590
+ key=f"download_button_{st.session_state.langues}_{st.session_state.timestamp}",
591
+ )
592
+
593
+ except Exception as e:
594
+ st.error(f"[AUDIO] - Erreur lors de l'exportation de l'audio : {str(e)}")
595
+ #finally:
596
+ # clear_inputs_garbages()
597
+ # if 'tmp_file' in locals():
598
+ # os.unlink(tmp_file.name)
599
+ ##st.session_state.rec_widget.close()
600
+
601
+
602
+ #if "rec_widget" in st.session_state:
603
+ # list_dir_obj = dir(st.session_state.rec_widget)
604
+ # for itl in list_dir_obj:
605
+ # if "__" not in itl:
606
+ # st.write(f"***{itl}*** :\n{getattr(st.session_state.rec_widget, itl).__doc__}")
607
+
608
  def main_page():
609
  """Page principale de l'application."""
610
 
 
629
  if "interface_language_select" not in st.session_state:
630
  st.session_state.interface_language_select = "English" # Langue par défaut
631
 
632
+ if "enable_tts_for_input_from_audio_record" not in st.session_state:
633
+ st.session_state["enable_tts_for_input_from_audio_record"] = False
634
+
635
+ if "autoplay_tts" not in st.session_state:
636
+ st.session_state["autoplay_tts"] = False
637
+
638
+ if "enable_tts_for_input_from_text_field" not in st.session_state:
639
+ st.session_state["enable_tts_for_input_from_text_field"] = False
640
+
641
+ if "tts_voice" not in st.session_state:
642
+ st.session_state["tts_voice"] = "onyx"
643
 
644
  # Initialisation de l'historique des messages avec le prompt système
645
  if "messages" not in st.session_state:
646
  st.session_state.messages = []
647
 
648
+ def on_languages_change() -> None:
649
+ #clear_inputs_garbages()
650
+ """Fonction de rappel pour le changement de langue(s) de destination."""
651
+ selected_language_names: List[str] = st.session_state.language_selector
652
+ st.session_state.selected_languages = [
653
+ {"language": lang, "iso-639-1": convert_language_name_to_iso6391(lang)}
654
+ for lang in selected_language_names
655
+ ]
656
+
657
+
658
+
659
+ # Configuration de la barre latérale
660
+ with st.sidebar:
661
+ st.logo("img/logo_2.png", icon_image="img/logo_2.png")
662
+ st.header(get_translation("sidebar_titre"))
663
+
664
+ if st.button("A"):
665
+ vote("A")
666
+
667
+ with st.expander(f"{get_translation('a_propos')}",
668
+ expanded=False,
669
+ icon="ℹ️"):
670
+ st.subheader(f"version: {__version__}")
671
+ st.info(get_translation("info_app"))
672
+
673
+
674
+ with st.expander(f"{get_translation('selection_langue')}",
675
+ expanded=True,
676
+ icon="🌐"):
677
+ # Conteneur pour la sélection de langue
678
+
679
+ # Sélection multiple des langues de destination
680
+ st.multiselect(
681
+ label=get_translation("langues_destination"),
682
+ placeholder=get_translation("placeholder_langues"),
683
+ options=SUPPORTED_LANGUAGES,
684
+ default=["English"],
685
+ key="language_selector",
686
+ max_selections=4,
687
+ on_change=on_languages_change,
688
+ format_func=lambda lang: f"{LANGUAGES_EMOJI.get(lang, '')} {lang}"
689
+ )
690
+
691
  with st.container(border=True):
692
  # Interface utilisateur pour le chat textuel
693
  st.session_state.user_input = st.chat_input(
694
  get_translation("entrez_message")
695
  )
696
+
697
+ st.experimental_audio_input("Record a voice message",on_change=recorder_released, key="rec_widget")
698
+ #audiorecorder(
699
+ # start_prompt=get_translation("cliquez_enregistrer"),
700
+ # stop_prompt=get_translation("cliquez_arreter"),
701
+ # pause_prompt=get_translation("cliquez_pause"),
702
+ # show_visualizer=True,
703
+ # key="vocal_chat_input"
704
+ #)
705
 
706
 
707
  if st.session_state.user_input:
 
813
  # ##
814
  audio_status.update(label=f"{get_translation('erreur_concatenation_audio')} : {str(e)}", state="error", expanded=True)
815
 
816
+ #clear_inputs_garbages()
817
  # Interface utilisateur pour l'enregistrement audio
818
  # st.write(f"🗣️ {get_translation('enregistrez_message')}")
819
 
820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
821
 
822
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
823
 
824
 
825
 
 
839
  delete_session_state_var(it_var_name)
840
 
841
 
842
+ #clear_inputs_garbages()
843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
844
 
845
 
846
 
847
  main_page()
848
+
requirements.txt CHANGED
@@ -1,6 +1,6 @@
1
- streamlit
2
  streamlit-audiorecorder
3
  streamlit-autorefresh
4
  replicate
5
  openai
6
- pydub
 
1
+ streamlit==1.39.0
2
  streamlit-audiorecorder
3
  streamlit-autorefresh
4
  replicate
5
  openai
6
+ pydub