Spaces:
Sleeping
Sleeping
Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212import gradio as grimport openpyxlimport osfrom datetime import datetimefrom pptx import Presentationimport PyPDF2from 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): """Convert Excel to formatted Markdown-style text.""" output = io.StringIO() workbook = openpyxl.load_workbook(excel_file) for idx, sheet_name in enumerate(workbook.sheetnames): if idx > 0: output.write("\n" + "-" * 70 + "\n\n") output.write(f"### {sheet_name}:\n") sheet = workbook[sheet_name] if sheet.max_row <= 1 and sheet.max_column <= 1: output.write("# No data in sheet\n\n") continue data = [] max_col_widths = [] non_empty_rows = [] non_empty_cols = [] for row_idx in range(1, sheet.max_row + 1): for col_idx in range(1, sheet.max_column + 1): cell_value = sheet.cell(row=row_idx, column=col_idx).value if cell_value: non_empty_rows.append(row_idx) non_empty_cols.append(col_idx) if not non_empty_rows or not non_empty_cols: output.write("# No data in sheet\n\n") continue min_row, max_row = min(non_empty_rows), max(non_empty_rows) min_col, max_col = min(non_empty_cols), max(non_empty_cols) max_col_widths = [0] * (max_col - min_col + 1) for row_idx in range(min_row, max_row + 1): row_data = [] for col_idx in range(min_col, max_col + 1): value = str(sheet.cell(row=row_idx, column=col_idx).value or "") row_data.append(value) col_pos = col_idx - min_col max_col_widths[col_pos] = max(max_col_widths[col_pos], len(value)) data.append(row_data) for row_idx, row in enumerate(data): if row_idx == 0: header_line = "| " + " | ".join(cell + " " * (max_col_widths[i] - len(cell)) for i, cell in enumerate(row)) + " |" output.write(header_line + "\n") separator_line = "|" + "|".join("-" * (width + 2) for width in max_col_widths) + "|" output.write(separator_line + "\n") data_line = "| " + " | ".join(cell + " " * (max_col_widths[i] - len(cell)) for i, cell in enumerate(row)) + " |" output.write(data_line + "\n") output.write("\n") return output.getvalue()
def convert_pptx_to_text(self, pptx_file, filename): """Convert PowerPoint to plain text.""" output = io.StringIO() prs = Presentation(pptx_file) output.write(f"# PowerPoint Presentation: {filename}\n\n") for slide_num, slide in enumerate(prs.slides, 1): output.write(f"## Slide {slide_num}\n") for shape in slide.shapes: if hasattr(shape, "text"): output.write(f"{shape.text}\n\n") return output.getvalue()
def convert_pdf_to_text(self, pdf_file, filename): """Convert PDF to plain text.""" output = io.StringIO() pdf_reader = PyPDF2.PdfReader(pdf_file) output.write(f"# PDF Document: {filename}\n\n") for page_num, page in enumerate(pdf_reader.pages, 1): output.write(f"## Page {page_num}\n") output.write(page.extract_text() + "\n\n") return output.getvalue()
def convert_docx_to_text(self, docx_file, filename): """Convert Word to plain text.""" output = io.StringIO() doc = Document(docx_file) output.write(f"# Word Document: {filename}\n\n") for para in doc.paragraphs: output.write(para.text + "\n\n") return output.getvalue()
def 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, None try: 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 file with 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.name logging.info(f"Created temporary file at: {temp_file_path}") try: result = None if 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_msg logging.info(f"Conversion successful, text length: {len(result) if result else 0}") # Create and return file for download output_filename = os.path.splitext(filename)[0] + ".txt" # Convert result to bytes for file download if 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), result else: logging.warning("No result generated") return "No result generated", None, None finally: # Clean up the temporary file if 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 interfacewith gr.Blocks(title="Multi-Format to TXT Converter") as app: gr.Markdown("# Multi-Format to TXT Converter by Heuristica.pl") gr.Markdown("Convert Excel, PowerPoint, PDF, and Word files to text format.") with 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 message status_output = gr.Textbox(label="Status", value="Ready to convert") # Info about supported formats gr.Markdown(""" ## Supported file formats: - **Excel**: .xlsx, .xls - **PowerPoint**: .pptx, .ppt - **PDF**: .pdf - **Word**: .docx, .doc ## How to use: 1. Upload a file using the file upload button 2. Click "Convert to TXT" 3. View the converted text and download the result """) # Setup the conversion process convert_button.click( fn=convert_file, inputs=[file_input], outputs=[text_output, file_output, status_output] )
# 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.pyDeleted-212