drewThomasson's picture
Update app.py
8998596 verified
import gradio as gr
import os
# Function to convert files using LibreOffice (soffice)
def convert_file(input_file, output_format):
# Get the absolute path to the input file
input_filepath = input_file.name
output_filename = f"{os.path.splitext(os.path.basename(input_filepath))[0]}.{output_format}"
output_filepath = os.path.join(os.getcwd(), output_filename)
# Run the LibreOffice command to convert the file using 'soffice'
command = f"soffice --headless --convert-to {output_format} \"{input_filepath}\" --outdir \"{os.getcwd()}\""
conversion_status = os.system(command)
# Check if the conversion was successful
if conversion_status == 0 and os.path.exists(output_filepath):
return output_filepath
else:
return "Error: Conversion failed."
# Supported formats from LibreOffice filters
supported_formats = [
"pdf", "doc", "docx", "html", "txt", "odt", "rtf", "ppt", "pptx", "xls", "xlsx"
]
# Gradio interface
def gradio_interface():
with gr.Blocks() as demo:
file_input = gr.File(label="Upload a file")
format_dropdown = gr.Dropdown(supported_formats, label="Select Output Format")
output_file = gr.File(label="Converted File")
convert_button = gr.Button("Convert")
convert_button.click(
fn=convert_file,
inputs=[file_input, format_dropdown],
outputs=output_file
)
return demo
if __name__ == "__main__":
gradio_interface().launch()