import streamlit as st from streamlit import elements import json import uuid import os from pytube import YouTube from moviepy.editor import VideoFileClip import openai from langchain.llms import OpenAI from langchain.chat_models import ChatOpenAI from langchain import PromptTemplate from langchain.prompts import ChatPromptTemplate import time from dotenv import load_dotenv, find_dotenv import eyed3 import os import wave from pydub import AudioSegment #############--------------- ID and Surveys ------------######################## # Generate unique user ID def generate_unique_id(): return str(uuid.uuid4()) # Save survey answers to a file def save_survey_answers(unique_id, answers): with open('survey_answers.json', 'w') as f: json.dump({unique_id: answers}, f) # f.write('\n') # Load all stored unique IDs def load_unique_ids(): try: with open('unique_ids.json', 'r') as f: return json.load(f) except FileNotFoundError: return [] # Save a unique ID def save_unique_id(unique_id): ids = load_unique_ids() ids.append(unique_id) with open('unique_ids.json', 'w') as f: json.dump(ids, f) #############--------------- Video transcription ------------######################## # Download video from URL def download_video(url, output_directory='./downloads'): try: yt = YouTube(url) video = yt.streams.get_highest_resolution() if not os.path.exists(output_directory): os.makedirs(output_directory) video.download(output_path=output_directory) return os.path.join(output_directory, video.default_filename), 'Video downloaded successfully.' except Exception as e: message = f'An error occurred: {e}' return None, message # Convert video to audio def convert_to_audio(video_path, output_directory='./converted_audio'): try: video = VideoFileClip(video_path) audio_filename = f"{os.path.basename(video_path).split('.')[0]}.wav" audio_path = os.path.join(output_directory, audio_filename) if not os.path.exists(output_directory): os.makedirs(output_directory) video.audio.write_audiofile(audio_path) message = 'Audio converted successfully.' return audio_path, message except Exception as e: message = f"An error occurred: {e}" return None, message # Transcribe audio # Take WAV file from downloads and save to converted audio folder # Load API key from .env file load_dotenv(find_dotenv()) openai.api_key = os.getenv('OPENAI_API_KEY') # Load the API key # Split long audio files into clips to be processed by Whisper API # def split_audio_pyaudio(audio_path, clip_duration_sec=30, overlap_duration_sec=3, output_folder='converted_audio/clips'): # clip_list = [] # file_name = os.path.basename(audio_path)[:-4] # # Determine the total duration of the audio file # if audio_path.endswith('.mp3'): # audio_file = eyed3.load(audio_path) # total_duration = audio_file.info.time_secs # elif audio_path.endswith('.wav'): # with wave.open(audio_path, 'rb') as wf: # n_frames = wf.getnframes() # framerate = wf.getframerate() # total_duration = n_frames / framerate # else: # raise ValueError("Unsupported audio format") # if not os.path.exists(output_folder): # os.makedirs(output_folder) # CHUNK = 1024 # FORMAT = pyaudio.paInt16 # CHANNELS = 2 # RATE = 44100 # clip_duration_samples = clip_duration_sec * RATE # overlap_samples = overlap_duration_sec * RATE # wf = wave.open(audio_path, 'rb') # p = pyaudio.PyAudio() # clip_number = 1 # for start_sample in range(0, int(total_duration * RATE), clip_duration_samples - overlap_samples): # frames = [] # for i in range(0, int(RATE / CHUNK * clip_duration_sec)): # data = wf.readframes(CHUNK) # if not data: # break # frames.append(data) # clip_path = f"{output_folder}/{file_name}_clip_{clip_number}.wav" # wf_clip = wave.open(clip_path, 'wb') # wf_clip.setnchannels(CHANNELS) # wf_clip.setsampwidth(p.get_sample_size(FORMAT)) # wf_clip.setframerate(RATE) # wf_clip.writeframes(b''.join(frames)) # wf_clip.close() # clip_list.append(clip_path) # clip_number += 1 # wf.close() # p.terminate() # return clip_list import os import wave def split_audio_wave(audio_path, clip_duration_sec=30, overlap_duration_sec=3, output_folder='converted_audio/clips'): clip_list = [] file_name = os.path.basename(audio_path)[:-4] if not audio_path.endswith('.wav'): raise ValueError("Only WAV format is supported") # Determine the total duration of the audio file with wave.open(audio_path, 'rb') as wf: n_frames = wf.getnframes() framerate = wf.getframerate() total_duration = n_frames / framerate n_channels = wf.getnchannels() width = wf.getsampwidth() if not os.path.exists(output_folder): os.makedirs(output_folder) clip_number = 1 for start_sample in range(0, n_frames, int(clip_duration_sec * framerate - overlap_duration_sec * framerate)): end_sample = start_sample + clip_duration_sec * framerate wf.setpos(start_sample) frames = wf.readframes(end_sample - start_sample) clip_path = f"{output_folder}/{file_name}_clip_{clip_number}.wav" with wave.open(clip_path, 'wb') as wf_clip: wf_clip.setnchannels(n_channels) wf_clip.setsampwidth(width) wf_clip.setframerate(framerate) wf_clip.writeframes(frames) clip_list.append(clip_path) clip_number += 1 return clip_list # Takes WAV audio clips and transcribes them and saves them to JSON def transcribe(audio_path): clip_path_list = split_audio_wave(audio_path) file_name = os.path.basename(audio_path)[:-4] transcribed_clips = [] # Ensure the transcript file is empty to start with with open(f'{file_name}.txt', 'w') as txt_file: pass for clip in clip_path_list: with wave.open(clip, 'rb') as wf: n_frames = wf.getnframes() framerate = wf.getframerate() clip_duration = n_frames / framerate if clip_duration < 0.1: print(f"Skipping short clip (less than 0.1 sec): {clip}") continue # Skip short clips with open(clip, 'rb') as audio_file: transcript = openai.Audio.transcribe( file=audio_file, model="whisper-1", response_format='text', temperature=0.0 ) transcribed_clips.append(transcript + '\n') full_transcript_str = ''.join(transcribed_clips) messages=[ {'role':'system', 'content':'''You are a robot that is specifically designed to figure out what language a transcript is in. When given a transcript, ONLY return the ISO-639-1 language code. Take your time and think this through.'''}, {'role': 'user', 'content': 'je suis américain'}, {'role': 'assistant', 'content': 'fr'}, {'role': 'user', 'content': full_transcript_str} ] response = openai.ChatCompletion.create( model='gpt-3.5-turbo-0613', messages=messages, temperature=0 ) language = response['choices'][0]['message']['content'] transcript_json = {'title': os.path.basename(audio_path)[:-4], 'transcript': full_transcript_str, 'language' : language} with open(f'transcript/{file_name}.json', 'w') as json_file: json.dump(transcript_json, json_file, indent=4) message = "Transcription process completed!" return transcript_json, message #############--------------- Teacher ------------######################## # Function to get plain English word for language code def get_language_word(language, openai_api_key=''): llm = OpenAI(model_name='gpt-3.5-turbo-0613', openai_api_key=st.session_state.api_key, temperature=0) template = '''Convert the ISO-639-1 language code into the plain english word for the language. ONLY return the english word for that language, nothing more. Here is the language code: {language} Take your time and think this through. Remember only respond with one word, the english word for the language.''' prompt = PromptTemplate( input_variables=['language'], template=template, ) final_prompt = prompt.format(language=language) return llm(final_prompt) # Function to create lesson outline def create_lesson_outline(transcript_json, learning_goal='learn new languague', num_words='5', openai_api_key=''): try: with open('lesson_format.txt', 'r') as txt_file: lesson_format = txt_file.read() except FileNotFoundError: return "Error: 'lesson_format.txt' not found. Please make sure it's in the current working directory." chat = ChatOpenAI(temperature=0.2, model='gpt-3.5-turbo-0613', openai_api_key=st.session_state.api_key) template_string = '''Create a lesson based on this title ```{title}```, following this transcript ```{transcript_text}```, and following this format ```{lesson_format}```. Keep in mind the student's learning goal ```{learning_goal}``` and the number of words they want to learn```{num_words}```. For context you are making a lesson plan based on the title of an audio clip taken from a youtube video. Again the title of the video is {title}. Take this into account when making the title of the lesson plan and teaching the concept. Only output the lesson plan, nothing more''' prompt_template = ChatPromptTemplate.from_template(template_string) messages = prompt_template.format_messages( lesson_format=lesson_format, transcript_text=transcript_json['transcript'], title=transcript_json['title'], learning_goal=learning_goal, num_words=num_words ) response = chat(messages) message = 'Lesson outline created successfully.' return response.content, message #############--------------- Chat bot ------------######################## # Initialize the chatbox state def initialize_chatbox(): if "messages" not in st.session_state: st.session_state["messages"] = [] # Add a message to the chatbox def add_to_chatbox(role, message): st.session_state.messages.append({"role": role, "content": message}) if role == "user": # If the message is from the user response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", prompt=message, max_tokens=150 # Limit the response to 150 tokens ) teacher_response = response.choices[0] # Extract the bot's response text st.session_state.messages.append({"role": "assistant", "content": teacher_response}) # Display the chatbox def display_chatbox(): st.markdown("