AkashKumarave commited on
Commit
2c0c380
·
verified ·
1 Parent(s): 30ea5f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -21
app.py CHANGED
@@ -1,34 +1,52 @@
1
- from fastapi import FastAPI, File, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import JSONResponse
4
  import pdfplumber
5
  from io import BytesIO
6
  import base64
7
  import uvicorn
 
 
 
 
 
8
 
9
  app = FastAPI()
10
 
11
  # Add CORS middleware
12
  app.add_middleware(
13
  CORSMiddleware,
14
- allow_origins=["*"], # Restrict in production
15
  allow_credentials=True,
16
  allow_methods=["*"],
17
  allow_headers=["*"],
18
  )
19
 
20
- # Root route to avoid 404 errors
21
  @app.get("/")
22
  async def root():
23
  return {"message": "PDF to Figma API"}
24
 
25
  @app.post("/api/convert")
26
- async def convert_pdf(file: bytes = File(...)):
27
  try:
 
 
 
 
 
 
 
 
28
  # Parse PDF with pdfplumber
29
- with pdfplumber.open(BytesIO(file)) as pdf:
 
 
 
 
30
  page = pdf.pages[0] # First page
31
  width, height = page.width, page.height
 
32
 
33
  # Initialize result
34
  result = {
@@ -53,28 +71,40 @@ async def convert_pdf(file: bytes = File(...)):
53
 
54
  # Extract images
55
  for img in page.images:
56
- img_data = img["stream"].get_data()
57
- result["images"].append({
58
- "data": base64.b64encode(img_data).decode('utf-8'),
59
- "x": img["x0"],
60
- "y": img["y0"],
61
- "width": img["width"],
62
- "height": img["height"]
63
- })
 
 
 
 
64
 
65
  # Extract shapes
66
  for curve in page.curves:
67
- path = " ".join([f"M {p['x']},{p['y']}" for p in curve["points"]])
68
- result["shapes"].append({
69
- "path": path,
70
- "x": curve["x0"],
71
- "y": curve["y0"],
72
- "color": {"r": 0, "g": 0, "b": 0}
73
- })
 
 
 
 
74
 
 
75
  return JSONResponse(content=result)
76
  except Exception as e:
77
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
78
 
79
  # Run uvicorn server
80
  if __name__ == "__main__":
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import JSONResponse
4
  import pdfplumber
5
  from io import BytesIO
6
  import base64
7
  import uvicorn
8
+ import logging
9
+
10
+ # Set up logging
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
 
14
  app = FastAPI()
15
 
16
  # Add CORS middleware
17
  app.add_middleware(
18
  CORSMiddleware,
19
+ allow_origins=["*"],
20
  allow_credentials=True,
21
  allow_methods=["*"],
22
  allow_headers=["*"],
23
  )
24
 
25
+ # Root route
26
  @app.get("/")
27
  async def root():
28
  return {"message": "PDF to Figma API"}
29
 
30
  @app.post("/api/convert")
31
+ async def convert_pdf(file: UploadFile = File(...)):
32
  try:
33
+ logger.info("Received file: %s", file.filename)
34
+
35
+ # Read the uploaded file
36
+ contents = await file.read()
37
+ if not contents:
38
+ logger.error("Empty file uploaded")
39
+ raise HTTPException(status_code=400, detail="Empty file uploaded")
40
+
41
  # Parse PDF with pdfplumber
42
+ with pdfplumber.open(BytesIO(contents)) as pdf:
43
+ if not pdf.pages:
44
+ logger.error("No pages found in PDF")
45
+ raise HTTPException(status_code=400, detail="No pages found in PDF")
46
+
47
  page = pdf.pages[0] # First page
48
  width, height = page.width, page.height
49
+ logger.info("Processing PDF page: width=%s, height=%s", width, height)
50
 
51
  # Initialize result
52
  result = {
 
71
 
72
  # Extract images
73
  for img in page.images:
74
+ try:
75
+ img_data = img["stream"].get_data()
76
+ result["images"].append({
77
+ "data": list(img_data),
78
+ "x": img["x0"],
79
+ "y": img["y0"],
80
+ "width": img["width"],
81
+ "height": img["height"]
82
+ })
83
+ except Exception as e:
84
+ logger.warning("Failed to extract image: %s", str(e))
85
+ continue
86
 
87
  # Extract shapes
88
  for curve in page.curves:
89
+ try:
90
+ path = " ".join([f"M {p['x']},{p['y']}" for p in curve["points"]])
91
+ result["shapes"].append({
92
+ "path": path,
93
+ "x": curve["x0"],
94
+ "y": curve["y0"],
95
+ "color": {"r": 0, "g": 0, "b": 0}
96
+ })
97
+ except Exception as e:
98
+ logger.warning("Failed to extract shape: %s", str(e))
99
+ continue
100
 
101
+ logger.info("PDF processing complete")
102
  return JSONResponse(content=result)
103
  except Exception as e:
104
+ logger.error("Failed to process PDF: %s", str(e))
105
+ raise HTTPException(status_code=500, detail=f"Failed to process PDF: {str(e)}")
106
+ finally:
107
+ await file.close()
108
 
109
  # Run uvicorn server
110
  if __name__ == "__main__":