Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines78910111277 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261274 unmodified lines1321331341351361371381391401411421431441451461471481491501516 unmodified linesfrom docx import Documentimport ioimport tempfileclass MultiConverter:def convert_excel_to_formatted_text(self, excel_file):77 unmodified linesdef convert_file(file):"""Process uploaded file and convert it to text"""try:converter = MultiConverter()filename = file.name_, file_ext = os.path.splitext(filename)file_ext = file_ext.lower()# Create a temporary filewith tempfile.NamedTemporaryFile(delete=False) as temp_file:temp_file.write(file.read())temp_file_path = temp_file.nametry:if file_ext in [".xlsx", ".xls"]:result = converter.convert_excel_to_formatted_text(temp_file_path)elif file_ext in [".pptx", ".ppt"]:result = converter.convert_pptx_to_text(temp_file_path, filename)elif file_ext == ".pdf":result = converter.convert_pdf_to_text(temp_file_path, filename)elif file_ext in [".docx", ".doc"]:result = converter.convert_docx_to_text(temp_file_path, filename)else:result = f"Unsupported file format: {file_ext}"# Create and return file for downloadoutput_filename = os.path.splitext(filename)[0] + ".txt"return result, output_filename, resultfinally:# Clean up the temporary fileif os.path.exists(temp_file_path):os.unlink(temp_file_path)except Exception as e:return f"Error converting file: {str(e)}", None, None# Create Gradio interface4 unmodified lineswith gr.Row():with gr.Column():file_input = gr.File(label="Upload a file (Excel, PowerPoint, PDF, or Word)")convert_button = gr.Button("Convert to TXT")with gr.Row():with gr.Column():text_output = gr.Textbox(label="Converted Text", lines=15)file_output = gr.File(label="Download Text File")# Setup the conversion processconvert_button.click(fn=convert_file,inputs=[file_input],outputs=[text_output, file_output, text_output])# Launch the appif __name__ == "__main__":app.launch()6 unmodified lines7891011121314151617181977 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651664 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112126 unmodified linesfrom docx import Documentimport ioimport tempfileimport logging# Konfiguracja logowanialogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')class MultiConverter:def convert_excel_to_formatted_text(self, excel_file):77 unmodified linesdef convert_file(file):"""Process uploaded file and convert it to text"""if file is None:logging.warning("No file provided")return "No file uploaded. Please select a file first.", None, Nonetry:logging.info(f"Converting file: {file.name}")converter = MultiConverter()filename = file.name_, file_ext = os.path.splitext(filename)file_ext = file_ext.lower()logging.info(f"File extension: {file_ext}")# Create a temporary filewith tempfile.NamedTemporaryFile(delete=False) as temp_file:file_content = file.read()logging.info(f"Read {len(file_content)} bytes from input file")temp_file.write(file_content)temp_file_path = temp_file.namelogging.info(f"Created temporary file at: {temp_file_path}")try:result = Noneif file_ext in [".xlsx", ".xls"]:logging.info("Processing Excel file")result = converter.convert_excel_to_formatted_text(temp_file_path)elif file_ext in [".pptx", ".ppt"]:logging.info("Processing PowerPoint file")result = converter.convert_pptx_to_text(temp_file_path, filename)elif file_ext == ".pdf":logging.info("Processing PDF file")result = converter.convert_pdf_to_text(temp_file_path, filename)elif file_ext in [".docx", ".doc"]:logging.info("Processing Word file")result = converter.convert_docx_to_text(temp_file_path, filename)else:error_msg = f"Unsupported file format: {file_ext}"logging.error(error_msg)result = error_msglogging.info(f"Conversion successful, text length: {len(result) if result else 0}")# Create and return file for downloadoutput_filename = os.path.splitext(filename)[0] + ".txt"# Convert result to bytes for file downloadif result:file_content = result.encode('utf-8')logging.info(f"Created output file: {output_filename}, size: {len(file_content)} bytes")return result, (output_filename, file_content), resultelse:logging.warning("No result generated")return "No result generated", None, Nonefinally:# Clean up the temporary fileif os.path.exists(temp_file_path):logging.info(f"Removing temporary file: {temp_file_path}")os.unlink(temp_file_path)else:logging.warning(f"Temporary file not found for deletion: {temp_file_path}")except Exception as e:error_msg = f"Error converting file: {str(e)}"logging.exception(error_msg)return error_msg, None, None# Create Gradio interface4 unmodified lineswith gr.Row():with gr.Column():file_input = gr.File(label="Upload a file (Excel, PowerPoint, PDF, or Word)")convert_button = gr.Button("Convert to TXT", variant="primary")with gr.Row():with gr.Column():text_output = gr.Textbox(label="Converted Text", lines=15)file_output = gr.File(label="Download Text File")# Add status messagestatus_output = gr.Textbox(label="Status", value="Ready to convert")# Setup the conversion processconvert_button.click(fn=convert_file,inputs=[file_input],outputs=[text_output, file_output, status_output])# Dodaj przykładowe pliki do demonstracji (opcjonalnie)gr.Examples(examples=[["example.xlsx"],["example.pdf"],["example.docx"],["example.pptx"],],inputs=[file_input],outputs=[text_output, file_output, status_output],fn=convert_file,cache_examples=False,)# Launch the appif __name__ == "__main__":try:logging.info("Starting the application")app.launch(debug=True, share=False)logging.info("Application stopped")except Exception as e:logging.exception(f"Error launching application: {str(e)}")
app.py+69-8