interfacechange / app.py
karthikmn's picture
Update app.py
d2124d2 verified
import os
import gradio as gr
import cairosvg
import datetime
import tempfile
# Folder paths
INPUT_FOLDER = "./input/"
OUTPUT_FOLDER = "./output/"
LOG_FOLDER = "./logs/"
SVG_OUTPUT = os.path.join(OUTPUT_FOLDER, "processed_diagram.svg")
PDF_OUTPUT = os.path.join(OUTPUT_FOLDER, "processed_diagram.pdf")
# Ensure required folders exist
os.makedirs(INPUT_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
os.makedirs(LOG_FOLDER, exist_ok=True)
# Function to log conversion steps
def log_conversion(status, input_pdf, output_svg, output_pdf):
log_path = os.path.join(LOG_FOLDER, "conversion_log.txt")
with open(log_path, "a") as log_file:
log_file.write(f"{datetime.datetime.now()} - Status: {status}\n")
log_file.write(f"Input PDF: {input_pdf}\n")
log_file.write(f"Output SVG: {output_svg}\n")
log_file.write(f"Output PDF: {output_pdf}\n\n")
# Function to convert PDF to SVG using cairosvg
def convert_pdf_to_svg(input_pdf, output_svg, width, height):
try:
# Use cairosvg to convert the PDF to SVG
cairosvg.svg2pdf(url=input_pdf, write_to=output_svg)
return True
except Exception as e:
print(f"Error converting PDF to SVG: {e}")
return False
# Gradio interface function
def process_pdf(uploaded_file, width, height):
try:
# Save uploaded file
input_pdf = os.path.join(INPUT_FOLDER, "uploaded_file.pdf")
with open(input_pdf, "wb") as f:
f.write(uploaded_file.read())
# Step 1: Convert PDF to SVG
if convert_pdf_to_svg(input_pdf, SVG_OUTPUT, width, height):
# Step 2: Convert SVG to PDF (assuming `convert_svg_to_pdf` exists)
convert_svg_to_pdf(SVG_OUTPUT, PDF_OUTPUT)
# Step 3: Log the process
log_conversion("Success", input_pdf, SVG_OUTPUT, PDF_OUTPUT)
# Return output files for download
return (SVG_OUTPUT, PDF_OUTPUT)
else:
return "Error converting PDF to SVG."
except Exception as e:
log_conversion("Failed", input_pdf, SVG_OUTPUT, PDF_OUTPUT)
return str(e)
# Gradio interface setup (only Width and Height)
inputs = [
gr.File(label="Upload your PDF file", type="filepath"),
gr.Number(value=8.0, label="Width (in inches)", precision=1), # Width input in inches
gr.Number(value=11.0, label="Height (in inches)", precision=1) # Height input in inches
]
outputs = [
gr.File(label="Download SVG", type="filepath"),
gr.File(label="Download PDF", type="filepath")
]
# Launch Gradio interface
gr.Interface(
fn=process_pdf,
inputs=inputs,
outputs=outputs,
live=True,
title="PDF to Editable SVG and PDF Converter",
description="Upload a PDF to convert it to both an editable SVG and a PDF with transformations applied."
).launch()