Spaces:
Build error
Build error
Update app.py
Browse files9 unmodified lines1011121314152 unmodified lines181920212223242526272829303132333435363738394041424344454647484950515253545556575859606116 unmodified lines78798081828384858687888990919 unmodified linesfrom pathlib import Pathimport shutil@st.cache_datadef save_uploaded_file(uploaded_file):"""Save uploaded file to a temporary directory and return the path"""2 unmodified linestemp_dir = tempfile.mkdtemp()# Get the file extensionfile_extension = Path(uploaded_file.name).suffixif not file_extension: # If no extension, default to .wavfile_extension = '.wav'# Create full path with original 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())# Verify file exists and has contentif not os.path.exists(temp_path):raise FileNotFoundError(f"Failed to save file at {temp_path}")if os.path.getsize(temp_path) == 0:raise ValueError("Saved file is empty")st.debug(f"File saved successfully at: {temp_path}")return temp_path, temp_direxcept Exception as e:st.error(f"Error saving file: {str(e)}")if temp_dir and os.path.exists(temp_dir):shutil.rmtree(temp_dir)return None, Nonedef process_audio_file(file_path, temp_dir):"""Process and potentially chunk the audio file"""try:# Verify file exists before processingif not os.path.exists(file_path):raise FileNotFoundError(f"Audio file not found at: {file_path}")st.debug(f"Processing audio file: {file_path}")# Load audio file with explicit formattry:audio = AudioSegment.from_file(file_path, format=Path(file_path).suffix[1:])except:# Fallback to automatic format detectionaudio = AudioSegment.from_file(file_path)# If file is small enough, return it as isif os.path.getsize(file_path) <= MAX_FILE_SIZE:16 unmodified lineschunk = chunk.set_frame_rate(16000) # Set sample rate to 16kHzchunk.export(chunk_path, format="mp3", parameters=["-q:a", "0"])# Verify chunk was created successfullyif not os.path.exists(chunk_path) or os.path.getsize(chunk_path) == 0:raise Exception(f"Failed to create chunk {i}")chunks.append(chunk_path)st.debug(f"Created chunk {i+1}/{num_chunks}")return chunksexcept Exception as e:st.error(f"Error processing audio: {str(e)}")return None9 unmodified lines101112131415161718192021222324252 unmodified lines282930313233343536373839404142434445464748495016 unmodified lines6768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522539 unmodified linesfrom pathlib import Pathimport shutil# Load environment variablesload_dotenv()# Initialize OpenAI clientclient = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))# ConstantsMAX_FILE_SIZE = 25 * 1024 * 1024 # 25MB in bytesCHUNK_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"""2 unmodified linestemp_dir = tempfile.mkdtemp()# Get the file extensionfile_extension = Path(uploaded_file.name).suffix# Create full path with original 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 audio fileaudio = AudioSegment.from_file(file_path)# If file is small enough, return it as isif os.path.getsize(file_path) <= MAX_FILE_SIZE:16 unmodified lineschunk = chunk.set_frame_rate(16000) # Set sample rate to 16kHzchunk.export(chunk_path, format="mp3", parameters=["-q:a", "0"])chunks.append(chunk_path)# Verify file exists and has sizeif 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 = client.audio.transcriptions.create(model="whisper-1",file=audio,response_format="verbose_json",timestamp_granularities=["segment"])# Adjust timestamps for this chunkfor 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 None# Combine all transcriptionsif transcript and all_segments:full_transcript = transcriptfull_transcript.segments = all_segmentsreturn full_transcriptreturn 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"""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 = client.chat.completions.create(model="gpt-4-turbo-preview",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.contentexcept Exception as e:st.error(f"Error generating lesson plan: {str(e)}")return Nonedef format_transcript_with_timestamps(transcript_data):"""Format transcript with timestamps in a readable format"""formatted_text = "# Lecture Transcript with Timestamps\n\n"for segment in transcript_data.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")# Create two columns with custom widthscol1, col2 = st.columns([1, 3])# Left column for upload (smaller)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):# Create tabs in the right column for different outputswith col2:tab1, tab2 = st.tabs(["π Transcript", "π Lesson Plan"])with st.spinner("Processing audio..."):# Save uploaded file and get temporary pathstemp_path, temp_dir = save_uploaded_file(uploaded_file)if temp_path and temp_dir:try:# Process and potentially chunk the audio filechunks = process_audio_file(temp_path, temp_dir)if chunks:# Transcribe chunkstranscript_data = transcribe_audio_chunks(chunks)if transcript_data:# Format transcript with timestampsformatted_transcript = format_transcript_with_timestamps(transcript_data)# Generate lesson planlesson_plan = generate_lesson_plan(transcript_data.text)# Display transcript in first tabwith tab1:st.markdown(formatted_transcript)# Download button for transcriptst.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")# Display lesson plan in second tabwith tab2:if lesson_plan:st.markdown(lesson_plan)# Download button for lesson planst.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:# Clean up temporary filescleanup_files(temp_dir)# Right column instructions when no file is uploadedif 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 bothSupported formats: MP3, WAV, M4ANote: Large files will be automatically processed in chunks.""")if __name__ == "__main__":main()
app.py+190-28