-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
875 lines (761 loc) · 30.6 KB
/
streamlit_app.py
File metadata and controls
875 lines (761 loc) · 30.6 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import gettext
import deepgram
import pandas as pd
import io
import os
import smtplib
from tempfile import mkdtemp
from dateutil import parser
from typing import Literal
import databases
import logins
import openai
from openai import OpenAI
from deepgram import DeepgramClient, PrerecordedOptions, FileSource
from pydub import AudioSegment
from st_audiorec import st_audiorec
import streamlit as st
from streamlit_option_menu import option_menu
import toml
st.set_page_config(
page_title="_(Roland'sTool)",
page_icon=("🤖"),
layout="wide",
initial_sidebar_state="expanded",
)
# Initializing session states
# This is a best practice to declare all session states upfront for clarity
if "password_ok" not in st.session_state:
st.session_state["password_ok"] = None
if "user" not in st.session_state:
st.session_state["user"] = None
if "deepgram_key" not in st.session_state:
st.session_state["deepgram_key"] = (
st.secrets["DEEPGRAM_API_KEY"] if "DEEPGRAM_API_KEY" in st.secrets else None
)
if "openai_key" not in st.session_state:
st.session_state["openai_key"] = (
st.secrets["OPENAI_API_KEY"] if "OPENAI_API_KEY" in st.secrets else None
)
if "readme_displayed" not in st.session_state:
st.session_state["readme_displayed"] = False
if "subtitles" not in st.session_state:
st.session_state["subtitles"] = None
if "data" not in st.session_state:
st.session_state["data"] = {}
global _ # Declare _ as global at the start of the function
_ = gettext.gettext # Default to built-in gettext for English
def load_language(lang_code):
global _ # Declare _ as global at the start of the function
if lang_code == "en":
_ = gettext.gettext # Default to built-in gettext for English
else:
mo_file_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"locales",
lang_code,
"LC_MESSAGES",
"messages.mo",
)
)
try:
with open(mo_file_path, "rb") as mo_file:
# Load the .mo file directly
localizator = gettext.GNUTranslations(mo_file)
localizator.install()
_ = (
localizator.gettext
) # Set the _ to the gettext function from localizator
except FileNotFoundError as e:
st.error(f"Exception loading MO file: {e}")
def choose_language(unique_id):
lang_choice = st.radio(
_("Choose Language"),
options=["English", "日本語"],
index=0,
key=f"lang_choice_radio_{unique_id}", # Ensure unique key
)
lang_code = "en" if lang_choice == "English" else "ja"
load_language(lang_code)
return lang_code # Return the selected language code
def display_readme(lang_code="en"):
load_language(lang_code) # This will set the _ function correctly
# Use the _() function directly on the strings to be translated
if not st.session_state["data"]:
welcome_text = _(
""
"\n"
"# Welcome to Roland Tools\n"
"\n"
"This app transcribe spoken words from any language then make useful notes"
" from it.\n"
" "
)
st.image("static/transcription.svg", width=500)
st.markdown(welcome_text)
file_name = "README_JP.md" if lang_code == "ja" else "README.md"
with open(file_name, "r") as file:
readme_content = file.read()
with st.expander(_("I need help!")):
st.markdown(readme_content)
def check_deepgram_credentials():
with st.sidebar:
if "DEEPGRAM_API_KEY" in st.secrets:
st.toast(_("The Deepgram credentials have been entered for you!"))
st.toast(_("You are all set!"))
os.environ["DEEPGRAM_API_KEY"] = st.secrets["DEEPGRAM_API_KEY"]
st.session_state["deepgram_key"] = st.secrets["DEEPGRAM_API_KEY"]
return True
else:
if not st.session_state.get("deepgram_key"):
deepgram_api_key = st.text_input(
_("Enter Deepgram API token:"), type="password"
)
if not deepgram_api_key:
st.warning(_("Please enter your credentials!"), icon="⚠️")
return False
else:
os.environ["DEEPGRAM_API_KEY"] = deepgram_api_key
st.session_state["deepgram_key"] = deepgram_api_key
st.success(_("Proceed to uploading your audio file!"), icon="👉")
return True
def check_openai_credentials():
with st.sidebar:
if "OPENAI_API_KEY" in st.secrets:
st.toast(_("The OpenAI credentials have been entered for you!"))
st.toast(_("You are all set!"))
openai.api_key = st.secrets["OPENAI_API_KEY"]
st.session_state["openai_key"] = st.secrets["OPENAI_API_KEY"]
return True
else:
if not st.session_state["openai_key"]:
openai.api_key = st.text_input(
_("Enter OpenAI API token:"), type="password"
)
if not (openai.api_key.startswith("sk-") and len(openai.api_key) == 51):
st.warning(_("Please enter your credentials!"), icon="⚠️")
return False
else:
st.session_state["openai_key"] = openai.api_key
st.success(_("Proceed to uploading your audio file!"), icon="👉")
return True
def transcription(
file_path,
language: str = "en",
prompt: str = "",
response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] = "text",
):
client = OpenAI()
# Open the file and pass the file handle directly
with open(file_path, "rb") as file_handle:
transcription_data = client.audio.transcriptions.create(
model="whisper-1",
file=file_handle, # Pass the file handle
language=language,
prompt=prompt,
response_format=response_format,
)
return transcription_data
# return "Transcription ok"
# Function to segment the audio file
@st.cache_data
def segment_audio(audio_file, segment_duration=60000):
temp_dir = mkdtemp()
file_name = "audio_segment.wav" # A generic name for the audio segment
temp_file_path = os.path.join(temp_dir, file_name)
audio_file.seek(0) # Ensure the file pointer is at the start
with open(temp_file_path, "wb") as f:
f.write(audio_file.read())
audio = AudioSegment.from_file(temp_file_path)
segments = []
for i in range(0, len(audio), segment_duration):
segment = audio[i : i + segment_duration]
segment_file_path = os.path.join(temp_dir, f"segment_{i//segment_duration}.mp3")
segment.export(segment_file_path, format="mp3")
segments.append(segment_file_path)
return segments
def deepgram_transcribe(file_path, language, prompt, response_format, diarize=True):
DEEPGRAM_API_KEY = st.session_state.get("deepgram_key")
if DEEPGRAM_API_KEY is None:
st.error("Deepgram API key is not set.")
return None
deepgram_client = DeepgramClient(DEEPGRAM_API_KEY)
try:
# Read the file content into memory
with open(file_path, "rb") as audio_file:
audio_data = audio_file.read()
# Create a file-like object from the audio data
audio_buffer = io.BytesIO(audio_data)
# Determine the mimetype based on the file extension
mimetype = "audio/wav" # default
if file_path.lower().endswith(".mp3"):
mimetype = "audio/mpeg"
elif file_path.lower().endswith(".flac"):
mimetype = "audio/flac"
# Add more mime types as needed
source = {"buffer": audio_buffer, "mimetype": mimetype}
options = PrerecordedOptions(
model="whisper-large",
smart_format=True,
language=language,
detect_language=True if language == "auto" else False,
diarize=diarize,
)
response = deepgram_client.listen.prerecorded.v("1").transcribe_file(
source, options
)
# Log the detected language if auto-detection was used
if language == "auto" and response.results.detected_language:
st.info(f"Detected language: {response.results.detected_language}")
# Process the response to format paragraphs with speaker labels
formatted_transcript = ""
for paragraph in (
response.results.channels[0].alternatives[0].paragraphs.paragraphs
):
speaker = f"Speaker {paragraph.speaker}: " if diarize else ""
formatted_transcript += f"{speaker}{paragraph.sentences[0].text}\n\n"
return formatted_transcript.strip()
except Exception as e:
st.error(f"An error occurred during transcription: {e}")
return None
def openai_completion(
input_text: str,
system_prompt: str = "You are a helpful assistant that always answers in markdown.",
format="text",
model: str = "gpt-4o",
temperature: float = 0,
):
client = OpenAI()
completion_data = client.chat.completions.create(
model=model,
temperature=temperature,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": input_text},
],
response_format={"type": format},
)
return completion_data.choices[0].message.content
# return "completion ok"
# Function to display full language selector and return iso code.
def get_language_choice():
language_options = {
"Japanese": "ja",
"English": "en",
"French": "fr",
"Spanish": "es",
"Thai": "th",
"Arabic": "ar",
"Chinese": "zh",
"Korean": "ko",
"Automatic": "auto",
}
selected_language_name = st.selectbox(
_("What is the language of the audio?"),
options=list(language_options.keys()), # Display language names
key="language_choice_selector",
)
selected_language_code = language_options[selected_language_name]
return selected_language_code
def get_prompt_choice():
prompt_options = toml.load("prompts.toml")
formatted_options = {
key: value["description"] for key, value in prompt_options.items()
}
return st.selectbox(
_("Choose prepared AI secretary intructions (Optional):"),
key="prompt_box",
options=formatted_options.values(),
format_func=lambda x: next(k for k, v in formatted_options.items() if v == x),
)
def record_audio_input():
file = {}
recorded_file = st_audiorec()
file["name"] = "recorded_file"
file["file"] = recorded_file
if recorded_file:
return file
# todo add the logic to upload a text file.
def upload_file():
files = [] # list of dictionaries
uploaded_files = st.file_uploader(
"File Uploader",
accept_multiple_files=True,
label_visibility="collapsed",
type=[
"flac",
"m4a",
"mp3",
"mp4",
"mpeg",
"mpga",
"oga",
"ogg",
"wav",
"webm",
],
)
for uf in uploaded_files:
file_dict = {"name": uf.name, "file": uf}
files.append(file_dict)
if uf.name not in st.session_state["data"]:
st.session_state["data"][uf.name] = {
"file_id": None,
"note": None,
"transcript": None,
}
st.session_state["data"][uf.name]["file_id"] = databases.add_uploaded_file(
st.session_state["user"].id, uf.name
)
return files if files else []
def upload_reader(uploads):
if uploads:
with st.expander("👂Audio file Uploaded"):
for upload in uploads:
if (
upload
and isinstance(upload, dict)
and "name" in upload
and "file" in upload
):
st.write("💽", upload["name"])
st.audio(upload["file"])
else:
st.warning("No files uploaded.")
def prepare_audio(files):
# Check if the files list is empty or contains empty dictionaries
if not files or all(not file_dict for file_dict in files):
# Optionally, you can return an empty dictionary or perform some other action
return {}
prepared_files = {}
for file_dict in files:
# Check if both 'name' and 'file' keys exist in the dictionary
if "name" in file_dict and "file" in file_dict:
file_name = file_dict["name"]
file_content = file_dict["file"]
# Check if file_content is a bytes object or an UploadedFile
if isinstance(file_content, bytes):
# If it's already a bytes object, use it directly
prepared_content = io.BytesIO(file_content)
else:
# If it's an UploadedFile, read it to get bytes
prepared_content = io.BytesIO(file_content.read())
prepared_files[file_name] = segment_audio(prepared_content)
else:
# Log or handle cases where the file_dict is not correctly formatted
st.warning(f"Skipped an improperly formatted file entry: {file_dict}")
return prepared_files
def transcribe_form():
with st.form(key="transcribe_form", clear_on_submit=False, border=True):
language = get_language_choice()
response_format = "srt" if st.toggle(_("Transcribe to subtitles")) else "text"
st.session_state["subtitles"] = response_format
diarize = st.checkbox(_("Enable speaker diarization"), value=False)
prompt = st.text_area(
_("Describe the audio (optional):"),
placeholder=_(
"This is a conversation between 2 people. Vocabulary: Tsunagaru, Roland Haller, Alice Ballé…"
),
help=_(
"This can help the transcription to be more accurate by providing context and vocabulary."
),
)
transcribe_button = st.form_submit_button(
_("Transcribe Audio"),
type="primary",
use_container_width=True,
)
return transcribe_button, language, response_format, prompt, diarize
def secretary_form(prepared_prompt):
with st.form(key="secretary_form", clear_on_submit=False, border=True):
secretary_prompt = st.text_area(
_("AI secretary instructions:"),
value=(f"{prepared_prompt}"),
help=_(
"Describe what you want your AI secretary to do with the transcribed text: make notes, a poem, a list of groceries, etc."
),
)
model = st.radio(
_("Model"),
["gpt-4o", "gpt-4o-mini"],
captions=[_("Best for most tasks"), _("Best for formatting")],
horizontal=True,
)
temperature = st.slider(
_("Originality"),
min_value=0.1,
max_value=2.0,
value=0.7,
step=0.1,
help=_(
"This is the originality(temperature) of the openai model. 0 for a deterministic model always answering the same from the same input, 2 is fully free crazy AI completely detached from the input. 0.7 is the default."
),
)
process_button = st.form_submit_button(
_("Process text"),
type="primary",
use_container_width=True,
)
is_festive = st.checkbox(_("I am feeling festive!"))
return process_button, is_festive, secretary_prompt, model, temperature
def set_transcription_ui():
st.title(_("🎧🤖 Transcribe Tool"))
tab_upload, tab_record = st.tabs([_("💽 Upload"), _("🎙️ Record")])
files = [] # Initialize files outside the tab contexts
with tab_upload:
files.extend(upload_file()) # Extend the existing files list
with tab_record:
recorded_file = record_audio_input()
if recorded_file: # Check if there is a recorded file
files.append(recorded_file)
if files: # Check if there are any files (uploaded or recorded)
upload_reader(files)
segments = prepare_audio(files)
transcribe_button_clicked, language, response_format, prompt, diarize = (
transcribe_form()
)
if transcribe_button_clicked:
return segments, language, prompt, response_format, diarize
else:
transcribe_button_warning = st.button(
_("Transcribe Audio"),
type="primary",
use_container_width=True,
)
if transcribe_button_warning:
st.error(_("please upload a file to transcribe…"))
def set_secretary_ui():
st.title(_("🤖📝 Secretary Tool"))
prepared_prompt = get_prompt_choice() or ""
process_button, is_festive, secretary_prompt, model, temperature = secretary_form(
prepared_prompt
)
if process_button:
return is_festive, secretary_prompt, model, temperature
def set_sidebar():
with st.sidebar:
col_logo, col_info = st.columns(2)
with col_logo:
st.image(
"static/logo.png",
width=200,
use_column_width=True,
)
with col_info:
# Call the function to display language selector
language = choose_language("col_info")
tab_application, tab_account = st.tabs(["🤖 Application", "⚙️ Account"])
with tab_application:
transcription_param = set_transcription_ui()
secretary_param = set_secretary_ui()
feedback()
with tab_account:
logins.logout()
logins.change_password()
return language, transcription_param, secretary_param # processed_text
def transcribe(files, language, prompt, response_format, diarize):
with st.spinner(_("Wait for it... our AI is listening!")):
st.image("static/writing.png", width=300)
for file_name, file_segments in files.items():
if file_name not in st.session_state["data"]:
st.session_state["data"][file_name] = {
"file_id": None,
"note": None,
"transcript": None,
}
try:
full_transcript = ""
for segment in file_segments:
segment_transcript = deepgram_transcribe(
segment, language, prompt, response_format, diarize
)
if segment_transcript:
full_transcript += segment_transcript + "\n\n"
st.session_state["data"][file_name]["transcript"] = (
full_transcript.strip()
)
except Exception as e:
st.error(_(f"An error occurred during transcription: {e}"))
if st.session_state["data"][file_name]["transcript"]:
databases.upsert_transcript(
st.session_state["data"][file_name]["file_id"],
st.session_state["data"][file_name]["transcript"],
)
st.toast("upsert done")
st.success("Done!")
return st.session_state["data"]
def display_transcription(texts):
st.title(_("🎧🤖 Transcription"))
for index, (name, trans) in enumerate(texts.items()):
if "transcript" in trans and trans["transcript"] is not None:
with st.expander(f"Transcript from {name}"):
download(
name, trans["transcript"], st.session_state["subtitles"], index
) # Pass only name and index to the download function
st.write(trans["transcript"])
delete(name, "transcript", f"{name}transcript")
# Function to parse datetime
def parse_datetime(dt_string):
return parser.parse(dt_string)
# Function to convert data to CSV
def convert_data(user_data):
# Prepare the data list
data = []
# Iterate through each file
for file in user_data["files"]:
file_name = file["file_name"]
for transcript in file["transcripts"]:
created_at = parse_datetime(str(transcript["created_at"]))
transcript_text = transcript["transcript_text"]
# Handle multiple notes
for note in file["notes"]:
note_text = note["note_text"]
data.append(
{
"Upload date": created_at,
"file name": file_name,
"transcript": transcript_text,
"note": note_text,
}
)
# Create DataFrame
df = pd.DataFrame(data)
st.download_button(
_("download"),
df.to_csv(),
file_name=f"{st.session_state['user'].name}history_data.csv",
)
def display_history():
user_data = databases.get_user_data(st.session_state["user"].username)
st.title(_("🕰️ History"))
# Iterate through files
for file in user_data["files"]:
# Format the date for the expander title
date_str = file["created_at"].strftime("%Y-%m-%d")
with st.expander(f"Date: {date_str} - {file['file_name']}"):
# Display file details
st.subheader("Transcripts")
st.table(file["transcripts"])
st.subheader("Notes")
st.table(file["notes"])
convert_data(user_data)
def display_notes(notes):
st.title(_("🤖📝 Notes"))
for index, (name, note_info) in enumerate(notes.items()):
if (
"note" in note_info and note_info["note"]
): # Check if note exists and is not empty
with st.expander(_(f"Secretary note from {name}")):
download(
name,
note_info["note"],
"note",
index,
) # Pass only name and index to the download function
st.write(note_info["note"])
delete(name, "note", f"{name}notes")
def secretary_process(
secretary_prompt: str,
model: str,
temperature: float,
):
notes = st.session_state["data"]
def process_completion(file_name, file_data):
if "transcript" in file_data and file_data["transcript"] is not None:
prompt = f"```\n{file_data['transcript']}``` \n{secretary_prompt}"
else:
prompt = secretary_prompt
completion = openai_completion(
input_text=prompt, model=model, temperature=temperature
)
return file_name, completion
with st.spinner(_("Wait for it... our AI is thinking!")):
st.image("static/thinking.png", width=300)
if notes:
# Parallel processing using ThreadPoolExecutor
with ThreadPoolExecutor() as executor:
future_to_file = {
executor.submit(process_completion, file_name, file_data): file_name
for file_name, file_data in notes.items()
}
for future in as_completed(future_to_file):
file_name = future_to_file[future]
try:
completion = future.result()
notes[completion[0]]["note"] = completion[1]
except Exception as e:
st.error(f"An error occurred: {e}")
else:
prompt = secretary_prompt
name = _("AI chat")
notes[name] = {"file_id": 999999999, "transcript": None, "note": None}
completion = openai_completion(
input_text=prompt, model=model, temperature=temperature
)
notes[name]["note"] = completion
st.session_state["data"].update(notes)
full_notes = st.session_state["data"]
for file_name, file_data in full_notes.items():
if "note" in file_data and file_data["note"] is not None:
databases.upsert_note(file_data["file_id"], file_data["note"])
st.toast("upserted note")
return full_notes
# Todo: Downloads only the transcript.
def download(file_name, content, type, index):
# Check if the file_name exists in the session state data
if file_name in st.session_state["data"]:
file_data = content
# Determine the file format based on the type of data
file_format = (
"srt" if st.session_state["subtitles"] == "srt" and type == "srt" else "txt"
)
download_file_name = (
f"{file_name}_{type if type != 'srt' else 'trasncript'}.{file_format}"
)
# Unique key for the download button, to avoid conflicts in Streamlit
unique_key = f"download_button_{file_name}_{index}_{datetime.now()}"
st.download_button(
label=_("Download"),
data=file_data,
file_name=download_file_name,
key=unique_key,
type="primary",
)
def delete(file_name, key, index):
unique_key = f"button_{file_name}_{index}"
if st.button(label=_("Delete"), key=unique_key):
# Check if file_name exists and key is valid
if (
file_name in st.session_state["data"]
and key in st.session_state["data"][file_name]
):
# Set the specific key (transcript or note) to None or empty string
st.session_state["data"][file_name][key] = None
# Optional: Clean up if both transcript and note are None or empty
if not any(st.session_state["data"][file_name].values()):
st.session_state["data"].pop(file_name)
st.rerun()
def feedback():
# Check if 'show_form' is already in the session state
if "show_form" not in st.session_state:
st.session_state["show_form"] = False
# Button to toggle the feedback form
if st.button(_("Write feedback")):
st.session_state["show_form"] = not st.session_state["show_form"]
# Feedback form will be displayed based on the 'show_form' state
if st.session_state["show_form"]:
with st.form(key="feedback_form"):
body_text = ""
sender = st.text_input(label=_("Name"), placeholder=_("Alice"))
subject = st.text_input(
label=_("Subject"), placeholder=_("This is awesome!")
)
message = "Message:\n " + st.text_area(
label="Feedback",
placeholder="I love everything about this app.",
key="message",
)
include_data = st.checkbox(
label="Include data",
key="data_checkbox",
)
if include_data:
body_text = (
message
+ "Data:\n "
+ (
str(st.session_state["data"])
if st.session_state["data"]
else "No data available"
)
)
elif not include_data:
body_text = message + "\n\nNo data shared"
submit_feedback = st.form_submit_button(_("Send Feedback"))
if submit_feedback:
if (
sender and subject and body_text
): # Simple validation to ensure fields are filled
with st.spinner(_("Sending feedback...")):
send_email(sender, subject, body_text)
st.success(_("Thank you for your feedback!"))
else:
st.error(_("Please fill in all fields."))
def send_email(sender, subject, body_text):
SMTP_SERVER = st.secrets["SMTP_SERVER"]
SMTP_PORT = st.secrets["SMTP_PORT"]
EMAIL_ADDRESS = st.secrets["EMAIL_ADDRESS"]
EMAIL_PASSWORD = st.secrets["EMAIL_PASSWORD"]
print("Parameters", SMTP_SERVER, SMTP_PORT, EMAIL_ADDRESS, EMAIL_PASSWORD)
print("arguments", sender, subject, body_text)
message = MIMEMultipart()
message["From"] = st.secrets["EMAIL_ADDRESS"]
message["To"] = st.secrets["EMAIL_ADDRESS"]
message["Subject"] = f"Roland's Tool feedback from {sender} on {subject}"
message.attach(MIMEText(body_text, "plain"))
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.ehlo()
server.starttls()
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
server.send_message(message)
print("Email sent successfully")
def main():
databases.load_users()
if not st.session_state["deepgram_key"] and not check_deepgram_credentials():
st.stop()
logged_in = logins.main()
if not logged_in:
st.stop()
language, transcription_param, secretary_param = set_sidebar()
# Get the selected language from the sidebar and then display the README in the main section
display_readme(language)
transcribed_texts = {}
notes = {}
# Transcription
if transcription_param:
files, language, response_format, prompt, diarize = transcription_param
transcribed_texts = transcribe(
files, language, response_format, prompt, diarize
)
st.session_state["data"].update(transcribed_texts)
# Secretary Processing
if secretary_param:
is_festive, secretary_prompt, model, temperature = secretary_param
notes = secretary_process(
secretary_prompt,
(model if model else "gpt-4o"),
temperature,
)
st.session_state["data"].update(notes)
if is_festive:
st.balloons()
# Display Logic
if "data" in st.session_state:
data_has_transcript = any(
"transcript" in item and item["transcript"]
for item in st.session_state["data"].values()
)
data_has_note = any(
"note" in item and item["note"]
for item in st.session_state["data"].values()
)
if data_has_transcript and data_has_note:
col_trans, col_note = st.columns(2)
with col_trans:
display_transcription(st.session_state["data"])
with col_note:
display_notes(st.session_state["data"])
elif data_has_transcript:
display_transcription(st.session_state["data"])
elif data_has_note:
display_notes(st.session_state["data"])
st.image("static/thumbsup.png", width=300)
if st.button(_("🕰️ History"), key="historybutton"):
display_history()
if __name__ == "__main__":
main()