Spaces:
Sleeping
Sleeping
raymondEDS commited on
Commit Β·
aa1280b
1
Parent(s): 104b6b9
Using pdf workaround
Browse files3 unmodified lines4567899 unmodified lines192021222324253 unmodified lines2930313233343536373839404142432 unmodified lines46474849505172 unmodified lines12412512612712812913015 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821838 unmodified lines19219319419519619744 unmodified lines24224324424524624724824925044 unmodified lines2952962972982993003013023035 unmodified lines30931031131231331431524 unmodified lines3403413423433443453463473483493503 unmodified linesimport base64from datetime import datetimeimport json# Page configurationst.set_page_config(9 unmodified linesif 'current_user' not in st.session_state:st.session_state.current_user = "User"def save_document_info(filename, file_content, file_type):"""Save document information to session state"""if 'documents' not in st.session_state.uploaded_documents:st.session_state.uploaded_documents['documents'] = []3 unmodified lines'upload_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),'file_type': file_type,'size': len(file_content),'content': file_content.decode('latin-1') if isinstance(file_content, bytes) else str(file_content)}st.session_state.uploaded_documents['documents'].append(document_info)def extract_pdf_text(pdf_file):"""Extract text from PDF file"""try:pdf_reader = PyPDF2.PdfReader(pdf_file)text = ""for page in pdf_reader.pages:text += page.extract_text() + "\n"2 unmodified linesst.error(f"Error reading PDF: {str(e)}")return ""def main():# Sidebar for navigationwith st.sidebar:72 unmodified linesst.markdown("---")# Add information about file uploadst.info("π‘ **Note:** File upload is optimized for Hugging Face Spaces. If you experience issues, try refreshing the page.")uploaded_file = st.file_uploader("Choose a PDF file",15 unmodified linesfor key, value in file_details.items():st.write(f"- {key}: {value}")# Extract and display PDF contentpdf_text = extract_pdf_text(uploaded_file)if pdf_text.strip():st.subheader("π Document Preview")with st.expander("View extracted text"):st.text_area("PDF Content", pdf_text, height=300)else:st.warning("β οΈ Could not extract text from this PDF. The file may be image-based or encrypted.")# Upload buttonif st.button("Upload Document", type="primary"):try:# Reset file pointer to beginninguploaded_file.seek(0)# Save document infosave_document_info(uploaded_file.name,uploaded_file.read(),"PDF")st.success(f"β Document '{uploaded_file.name}' uploaded successfully!")st.balloons()# Clear the file uploaderst.rerun()except Exception as e:st.error(f"β Error uploading document: {str(e)}")st.info("π‘ Try uploading a smaller file or refresh the page.")except Exception as e:st.error(f"β Error processing file: {str(e)}")8 unmodified lines- Avoid password-protected PDFs- If upload fails, try refreshing the page**Supported formats:** PDF only""")44 unmodified linesst.write(f"**Uploaded:** {doc['upload_time']}")st.write(f"**Size:** {doc['size']} bytes")# Display content if availableif 'content' in doc and doc['content']:st.text_area("Document Content", doc['content'], height=400, key=f"content_{i}")st.markdown("---")44 unmodified linesst.write(f"**Uploaded:** {doc['upload_time']}")st.write(f"**Size:** {doc['size']} bytes")# Display content if availableif 'content' in doc and doc['content']:st.text_area("Document Content", doc['content'], height=400, key=f"lib_content_{i}")st.markdown("---")5 unmodified linesst.subheader("π§ System Information")st.write("**Version:** Dev LMS v1.0")st.write("**Features:**")st.write("- PDF document upload")st.write("- Document search and preview")st.write("- Document library")st.write("- Session-based storage")24 unmodified lines# Clear data optionif st.button("ποΈ Clear All Data"):if st.session_state.uploaded_documents.get('documents'):st.session_state.uploaded_documents['documents'] = []st.success("All documents have been cleared!")st.rerun()else:st.info("No documents to clear.")if __name__ == "__main__":main()3 unmodified lines45678910119 unmodified lines212223242526273 unmodified lines31323334353637383940414243444546474849505152535455565758592 unmodified lines626364656667686970717273747572 unmodified lines14814915015115215315415 unmodified lines1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212228 unmodified lines23123223323423523623723823924024144 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031144 unmodified lines3563573583593603613623633643653663673683693703713723733743753763773783793803815 unmodified lines38738838939039139239324 unmodified lines4184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644653 unmodified linesimport base64from datetime import datetimeimport jsonimport tempfileimport os# Page configurationst.set_page_config(9 unmodified linesif 'current_user' not in st.session_state:st.session_state.current_user = "User"def save_document_info(filename, file_content, file_type, temp_path=None):"""Save document information to session state"""if 'documents' not in st.session_state.uploaded_documents:st.session_state.uploaded_documents['documents'] = []3 unmodified lines'upload_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),'file_type': file_type,'size': len(file_content),'content': file_content.decode('latin-1') if isinstance(file_content, bytes) else str(file_content),'temp_path': temp_path # Store temp path for later use}st.session_state.uploaded_documents['documents'].append(document_info)def extract_pdf_text_from_temp(temp_path):"""Extract text from PDF file using temporary file path"""try:with open(temp_path, "rb") as pdf_file:pdf_reader = PyPDF2.PdfReader(pdf_file)text = ""for page in pdf_reader.pages:text += page.extract_text() + "\n"return textexcept Exception as e:st.error(f"Error reading PDF: {str(e)}")return ""def extract_pdf_text_from_memory(uploaded_file):"""Extract text from PDF file in memory"""try:pdf_reader = PyPDF2.PdfReader(uploaded_file)text = ""for page in pdf_reader.pages:text += page.extract_text() + "\n"2 unmodified linesst.error(f"Error reading PDF: {str(e)}")return ""def cleanup_temp_file(temp_path):"""Clean up temporary file"""try:if temp_path and os.path.exists(temp_path):os.remove(temp_path)except Exception as e:st.warning(f"Could not clean up temporary file: {str(e)}")def main():# Sidebar for navigationwith st.sidebar:72 unmodified linesst.markdown("---")# Add information about file uploadst.info("π‘ **Note:** File upload uses temporary storage for better compatibility with Hugging Face Spaces.")uploaded_file = st.file_uploader("Choose a PDF file",15 unmodified linesfor key, value in file_details.items():st.write(f"- {key}: {value}")# Create temporary file for better PDF processingtemp_path = Nonetry:with tempfile.NamedTemporaryFile(mode="wb", suffix=".pdf", delete=False) as temp:bytes_data = uploaded_file.getvalue()temp.write(bytes_data)temp_path = temp.namest.success(f"π File temporarily stored at: {temp_path}")# Extract and display PDF content using temporary filepdf_text = extract_pdf_text_from_temp(temp_path)if pdf_text.strip():st.subheader("π Document Preview")with st.expander("View extracted text"):st.text_area("PDF Content", pdf_text, height=300)else:st.warning("β οΈ Could not extract text from this PDF. The file may be image-based or encrypted.")# Upload buttonif st.button("Upload Document", type="primary"):try:# Save document info with temporary file pathsave_document_info(uploaded_file.name,bytes_data,"PDF",temp_path)st.success(f"β Document '{uploaded_file.name}' uploaded successfully!")st.balloons()# Clear the file uploaderst.rerun()except Exception as e:st.error(f"β Error uploading document: {str(e)}")st.info("π‘ Try uploading a smaller file or refresh the page.")# Clean up temp file on errorcleanup_temp_file(temp_path)except Exception as e:st.error(f"β Error creating temporary file: {str(e)}")st.info("π‘ Please try uploading a different PDF file.")cleanup_temp_file(temp_path)except Exception as e:st.error(f"β Error processing file: {str(e)}")8 unmodified lines- Avoid password-protected PDFs- If upload fails, try refreshing the page**Technical details:**- Files are temporarily stored on the server- Text extraction uses temporary file processing- Automatic cleanup of temporary files**Supported formats:** PDF only""")44 unmodified linesst.write(f"**Uploaded:** {doc['upload_time']}")st.write(f"**Size:** {doc['size']} bytes")# Check if we have a temporary file path for better content extractionif doc.get('temp_path') and os.path.exists(doc['temp_path']):try:# Extract fresh content from temporary filefresh_content = extract_pdf_text_from_temp(doc['temp_path'])if fresh_content.strip():st.text_area("Document Content (Fresh Extract)", fresh_content, height=400, key=f"fresh_content_{i}")else:# Fall back to stored contentif 'content' in doc and doc['content']:st.text_area("Document Content (Stored)", doc['content'], height=400, key=f"content_{i}")except Exception as e:st.warning(f"Could not read from temporary file: {str(e)}")# Fall back to stored contentif 'content' in doc and doc['content']:st.text_area("Document Content (Stored)", doc['content'], height=400, key=f"content_{i}")else:# Display stored contentif 'content' in doc and doc['content']:st.text_area("Document Content", doc['content'], height=400, key=f"content_{i}")st.markdown("---")44 unmodified linesst.write(f"**Uploaded:** {doc['upload_time']}")st.write(f"**Size:** {doc['size']} bytes")# Check if we have a temporary file path for better content extractionif doc.get('temp_path') and os.path.exists(doc['temp_path']):try:# Extract fresh content from temporary filefresh_content = extract_pdf_text_from_temp(doc['temp_path'])if fresh_content.strip():st.text_area("Document Content (Fresh Extract)", fresh_content, height=400, key=f"lib_fresh_content_{i}")else:# Fall back to stored contentif 'content' in doc and doc['content']:st.text_area("Document Content (Stored)", doc['content'], height=400, key=f"lib_content_{i}")except Exception as e:st.warning(f"Could not read from temporary file: {str(e)}")# Fall back to stored contentif 'content' in doc and doc['content']:st.text_area("Document Content (Stored)", doc['content'], height=400, key=f"lib_content_{i}")else:# Display stored contentif 'content' in doc and doc['content']:st.text_area("Document Content", doc['content'], height=400, key=f"lib_content_{i}")st.markdown("---")5 unmodified linesst.subheader("π§ System Information")st.write("**Version:** Dev LMS v1.0")st.write("**Features:**")st.write("- PDF document upload with temporary storage")st.write("- Document search and preview")st.write("- Document library")st.write("- Session-based storage")24 unmodified lines# Clear data optionif st.button("ποΈ Clear All Data"):if st.session_state.uploaded_documents.get('documents'):# Clean up temporary files before clearing datadocuments = st.session_state.uploaded_documents['documents']for doc in documents:if doc.get('temp_path'):cleanup_temp_file(doc['temp_path'])st.session_state.uploaded_documents['documents'] = []st.success("All documents and temporary files have been cleared!")st.rerun()else:st.info("No documents to clear.")st.markdown("---")# Cleanup temporary files optionif st.button("π§Ή Cleanup Temporary Files"):documents = st.session_state.uploaded_documents.get('documents', [])cleaned_count = 0for doc in documents:if doc.get('temp_path') and not os.path.exists(doc['temp_path']):# Remove temp_path reference if file doesn't existdoc.pop('temp_path', None)cleaned_count += 1if cleaned_count > 0:st.success(f"Cleaned up {cleaned_count} missing temporary file references!")else:st.info("No cleanup needed - all temporary files are properly managed.")st.markdown("---")# System statusst.subheader("π System Status")documents = st.session_state.uploaded_documents.get('documents', [])temp_files_count = sum(1 for doc in documents if doc.get('temp_path') and os.path.exists(doc['temp_path']))col1, col2 = st.columns(2)with col1:st.metric("Total Documents", len(documents))with col2:st.metric("Active Temp Files", temp_files_count)if __name__ == "__main__":main()
src/streamlit_app.py+161-46