Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import streamlit as stfrom utils import split_audio, transcribe_audio, generate_lesson_planimport osimport openai# Set up OpenAI API keyopenai.api_key = os.getenv("OPENAI_API_KEY")st.title("Lecture Notes Generator")st.write("Upload an audio recording of the lecture.")# Create a two-column layoutcol1, col2 = st.columns([1, 2])with col1:# File upload for audioaudio_file = st.file_uploader("Choose an audio file (max 25MB)", type=["mp3", "wav"])if st.button("Generate Notes"):if audio_file is not None:# Save the uploaded filewith open("uploaded_audio.mp3", "wb") as f:f.write(audio_file.getbuffer())# Split audio into chunkschunks = split_audio("uploaded_audio.mp3")# Transcribe audiotranscriptions, timestamps = transcribe_audio(chunks)# Generate lesson plan from the transcriptionlesson_plan = generate_lesson_plan(transcriptions)# Display results in the second columnwith col2:st.subheader("Transcription with Timestamps")for ts, text in zip(timestamps, transcriptions):st.write(f"{ts}: {text}")st.subheader("Generated Lesson Plan")st.markdown(lesson_plan)else:st.error("Please upload an audio file.")with col2:# Initially emptyst.subheader("Lecture Notes and Lesson Plan")st.write("Upload an audio file to generate notes.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223import streamlit as stimport openaiimport osfrom datetime import datetimeimport jsonfrom dotenv import load_dotenvfrom pydub import AudioSegmentimport tempfileimport mathfrom pathlib import Pathimport shutil# Load environment variablesload_dotenv()# Initialize OpenAI clientopenai.api_key = os.getenv("OPENAI_API_KEY")# ConstantsMAX_FILE_SIZE = 25 * 1024 * 1024 # 25MB in bytes (OpenAI API limit)CHUNK_LENGTH = 10 * 60 * 1000 # 10 minutes in milliseconds@st.cache_datadef save_uploaded_file(uploaded_file):"""Save uploaded file to a temporary directory and return the path"""try:temp_dir = tempfile.mkdtemp() # Create temporary directoryfile_extension = Path(uploaded_file.name).suffix # Get file extensiontemp_path = os.path.join(temp_dir, f"input_audio{file_extension}")# Save uploaded filewith open(temp_path, "wb") as f:f.write(uploaded_file.getvalue())return temp_path, temp_direxcept Exception as e:st.error(f"Error saving file: {str(e)}")return None, Nonedef process_audio_file(file_path, temp_dir):"""Process and potentially chunk the audio file"""try:# Load the audio file using pydubaudio = AudioSegment.from_file(file_path)# If file size is under the limit, return as a single chunkif os.path.getsize(file_path) <= MAX_FILE_SIZE:return [file_path]# Otherwise, chunk the audio into smaller partschunks = []total_length = len(audio)num_chunks = math.ceil(total_length / CHUNK_LENGTH)for i in range(num_chunks):start_time = i * CHUNK_LENGTHend_time = min((i + 1) * CHUNK_LENGTH, total_length)chunk = audio[start_time:end_time]chunk_path = os.path.join(temp_dir, f"chunk_{i}.mp3")# Export chunk with adjustmentschunk = chunk.set_channels(1) # Convert to monochunk = chunk.set_frame_rate(16000) # Set sample rate to 16kHzchunk.export(chunk_path, format="mp3", parameters=["-q:a", "0"])chunks.append(chunk_path)if not os.path.exists(chunk_path) or os.path.getsize(chunk_path) == 0:raise Exception(f"Failed to create chunk {i}")return chunksexcept Exception as e:st.error(f"Error processing audio: {str(e)}")return Nonedef transcribe_audio_chunks(chunks):"""Transcribe audio chunks and combine transcriptions"""all_segments = []current_time_offset = 0for i, chunk_path in enumerate(chunks):try:st.write(f"Processing chunk {i+1} of {len(chunks)}...")with open(chunk_path, "rb") as audio:transcript = openai.Audio.transcribe(model="whisper-1",file=audio,response_format="verbose_json")for segment in transcript['segments']:segment['start'] += current_time_offsetsegment['end'] += current_time_offsetall_segments.extend(transcript['segments'])# Update time offset for next chunkcurrent_time_offset += len(AudioSegment.from_file(chunk_path)) / 1000 # Convert to secondsexcept Exception as e:st.error(f"Error in transcription of chunk {i+1}: {str(e)}")return Noneif all_segments:return all_segmentsreturn Nonedef format_timestamp(seconds):"""Convert seconds to HH:MM:SS format"""hours = int(seconds // 3600)minutes = int((seconds % 3600) // 60)seconds = int(seconds % 60)return f"{hours:02d}:{minutes:02d}:{seconds:02d}"def generate_lesson_plan(transcript):"""Generate a structured lesson plan from the transcript using GPT-4"""try:system_prompt = """You are an educational content expert. Generate a detailed lesson plan from the lecture transcript.The lesson plan should include:1. Main Topics2. Subtopics3. Key Learning Objectives4. Important ConceptsFormat the output in markdown with clear hierarchical structure."""response = openai.ChatCompletion.create(model="gpt-4-turbo",messages=[{"role": "system", "content": system_prompt},{"role": "user", "content": f"Generate a lesson plan from this transcript:\n{transcript}"}],temperature=0.3,max_tokens=2000)return response.choices[0]['message']['content']except Exception as e:st.error(f"Error generating lesson plan: {str(e)}")return Nonedef format_transcript_with_timestamps(segments):"""Format transcript with timestamps in a readable format"""formatted_text = "# Lecture Transcript with Timestamps\n\n"for segment in segments:start_time = format_timestamp(segment['start'])formatted_text += f"**[{start_time}]** {segment['text']}\n\n"return formatted_textdef cleanup_files(temp_dir):"""Safely clean up temporary files"""try:if temp_dir and os.path.exists(temp_dir):shutil.rmtree(temp_dir)except Exception as e:st.warning(f"Warning: Could not clean up temporary files: {str(e)}")# Streamlit UIdef main():st.set_page_config(page_title="Lecture Notes Generator", layout="wide")st.title("π Lecture Notes Generator")col1, col2 = st.columns([1, 3])with col1:st.header("Upload Recording")uploaded_file = st.file_uploader("Choose an audio file", type=['mp3', 'wav', 'm4a'])if uploaded_file:st.audio(uploaded_file)file_size = uploaded_file.size / (1024 * 1024) # Convert to MBst.info(f"File size: {file_size:.2f} MB")if st.button("Generate Notes", type="primary", use_container_width=True):with col2:tab1, tab2 = st.tabs(["π Transcript", "π Lesson Plan"])with st.spinner("Processing audio..."):temp_path, temp_dir = save_uploaded_file(uploaded_file)if temp_path and temp_dir:try:chunks = process_audio_file(temp_path, temp_dir)if chunks:transcript_data = transcribe_audio_chunks(chunks)if transcript_data:formatted_transcript = format_transcript_with_timestamps(transcript_data)lesson_plan = generate_lesson_plan(formatted_transcript)with tab1:st.markdown(formatted_transcript)st.download_button(label="Download Transcript",data=formatted_transcript,file_name=f"transcript_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md",mime="text/markdown")with tab2:if lesson_plan:st.markdown(lesson_plan)st.download_button(label="Download Lesson Plan",data=lesson_plan,file_name=f"lesson_plan_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md",mime="text/markdown")finally:cleanup_files(temp_dir)if not uploaded_file:with col2:st.info("""π Start by uploading an audio file on the left side.The system will automatically:1. Transcribe the lecture with timestamps2. Generate a structured lesson plan3. Provide downloadable versions of both""")if __name__ == "__main__":main()
app.py+209-34