QCM-converter / app.py
TiH0's picture
Update app.py
b1ffdf1 verified
from fastapi import FastAPI, File, UploadFile, Form
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
import tempfile
import os
import shutil
from pathlib import Path
# Import your conversion function
from converter import process_excel_to_word
app = FastAPI(title="Quiz Converter API")
# Enable CORS for GitHub Pages
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, replace with your GitHub Pages URL
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {
"message": "Quiz Converter API",
"status": "running",
"endpoints": {
"convert": "/convert (POST)"
}
}
@app.post("/convert")
async def convert_excel_to_word(
file: UploadFile = File(...),
use_two_columns: bool = Form(True),
add_separator_line: bool = Form(True)
):
"""
Convert Excel quiz file to Word document
"""
# Validate file extension
if not file.filename.endswith('.xlsx'):
return {"error": "Only .xlsx files are supported"}, 400
# Create temporary files (not using context manager to avoid premature deletion)
temp_dir = tempfile.mkdtemp()
try:
temp_dir_path = Path(temp_dir)
# Save uploaded file
input_path = temp_dir_path / file.filename
with open(input_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# Generate output filename
output_filename = file.filename.replace('.xlsx', '_converted.docx')
output_path = temp_dir_path / output_filename
# Run the conversion
process_excel_to_word(
str(input_path),
str(output_path),
use_two_columns=use_two_columns,
add_separator_line=add_separator_line,
balance_method="dynamic"
)
# Read the file into memory before deleting temp directory
with open(output_path, "rb") as f:
file_content = f.read()
# Clean up temp directory
shutil.rmtree(temp_dir)
# Create a temporary file for the response
final_temp = tempfile.NamedTemporaryFile(delete=False, suffix='.docx')
final_temp.write(file_content)
final_temp.close()
# Return the file and schedule cleanup
return FileResponse(
path=final_temp.name,
filename=output_filename,
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
background=None # File will be cleaned up by OS eventually
)
except Exception as e:
# Clean up temp directory on error
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
return {"error": f"Conversion failed: {str(e)}"}, 500
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)