main.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import os
  2. import subprocess
  3. from typing import Optional
  4. from fastapi import FastAPI, UploadFile, HTTPException
  5. from fastapi.responses import JSONResponse, FileResponse
  6. from fastapi.staticfiles import StaticFiles
  7. from obs import ObsClient
  8. from dotenv import load_dotenv
  9. # Load environment variables
  10. load_dotenv()
  11. app = FastAPI()
  12. # Mount static files
  13. app.mount("/static", StaticFiles(directory="static"), name="static")
  14. # OBS configuration
  15. ACCESS_KEY = os.getenv('OBS_ACCESS_KEY')
  16. SECRET_KEY = os.getenv('OBS_SECRET_KEY')
  17. ENDPOINT = os.getenv('OBS_ENDPOINT')
  18. BUCKET = os.getenv('OBS_BUCKET')
  19. # File paths
  20. UPLOAD_DIR = "/app/uploads"
  21. PROCESSED_DIR = "/app/processed"
  22. # Ensure directories exist
  23. os.makedirs(UPLOAD_DIR, exist_ok=True)
  24. os.makedirs(PROCESSED_DIR, exist_ok=True)
  25. def get_obs_client() -> ObsClient:
  26. return ObsClient(
  27. access_key_id=ACCESS_KEY,
  28. secret_access_key=SECRET_KEY,
  29. server=ENDPOINT
  30. )
  31. @app.get("/")
  32. async def root():
  33. return FileResponse("static/index.html")
  34. @app.post("/convert")
  35. async def convert_eps_to_svg(file: UploadFile):
  36. # Check file size (10MB limit)
  37. file_size = 0
  38. content = await file.read()
  39. file_size = len(content)
  40. if file_size > 10 * 1024 * 1024: # 10MB
  41. raise HTTPException(status_code=400, detail="File too large. Maximum size is 10MB")
  42. # Check file extension
  43. if not file.filename.lower().endswith('.eps'):
  44. raise HTTPException(status_code=400, detail="Only EPS files are accepted")
  45. try:
  46. # Save uploaded file
  47. input_path = os.path.join(UPLOAD_DIR, file.filename)
  48. with open(input_path, "wb") as f:
  49. f.write(content)
  50. # Generate output paths
  51. base_name = os.path.splitext(file.filename)[0]
  52. temp_svg = os.path.join(PROCESSED_DIR, f"{base_name}_temp.svg")
  53. final_svg = os.path.join(PROCESSED_DIR, f"{base_name}.svg")
  54. # Convert EPS to SVG
  55. subprocess.run(['eps2svg', input_path, temp_svg], check=True)
  56. # Optimize SVG using scour
  57. subprocess.run(['scour', '-i', temp_svg, '-o', final_svg], check=True)
  58. # Upload to OBS
  59. obs_client = get_obs_client()
  60. obs_key = f"svg/{base_name}.svg"
  61. with open(final_svg, 'rb') as f:
  62. obs_client.putContent(BUCKET, obs_key, f.read())
  63. # Clean up files
  64. os.remove(input_path)
  65. os.remove(temp_svg)
  66. os.remove(final_svg)
  67. return JSONResponse({
  68. "status": "success",
  69. "message": "File processed successfully",
  70. "obs_key": obs_key
  71. })
  72. except subprocess.CalledProcessError as e:
  73. raise HTTPException(status_code=500, detail=f"Error processing file: {str(e)}")
  74. except Exception as e:
  75. raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
  76. @app.get("/health")
  77. def health_check():
  78. return {"status": "healthy"}