m8chaa commited on
Commit
59fb6b1
·
1 Parent(s): e175ed2

re-sheet initiated

Browse files
Files changed (4) hide show
  1. Dockerfile +11 -0
  2. books.json +32 -0
  3. main.py +86 -0
  4. requirements.txt +5 -0
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ WORKDIR /code
4
+
5
+ COPY ./requirements.txt /code/requirements.txt
6
+
7
+ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
8
+
9
+ COPY . .
10
+
11
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
books.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "Harry Potter",
4
+ "genre": "fiction",
5
+ "price": 15.0,
6
+ "book_id": "e1b7e31916f64bd3badd98b9e34cc5c3"
7
+ },
8
+ {
9
+ "name": "The Great Gatsby",
10
+ "genre": "fiction",
11
+ "price": 15.0,
12
+ "book_id": "1759c5e1cf4b4e26b7dd41c7d2af7c33"
13
+ },
14
+ {
15
+ "name": "Frankenstein",
16
+ "genre": "fiction",
17
+ "price": 10.0,
18
+ "book_id": "f4b7f7f488334155831a9656ba373530"
19
+ },
20
+ {
21
+ "name": "Atomic Habits",
22
+ "genre": "non-fiction",
23
+ "price": 30.0,
24
+ "book_id": "6e72714965f94d0c9600277bb7e5ba99"
25
+ },
26
+ {
27
+ "name": "A Wild Sheep Chase",
28
+ "genre": "fiction",
29
+ "price": 15.0,
30
+ "book_id": "58bfb9a684724846bd7f69688c6f09c9"
31
+ }
32
+ ]
main.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, UploadFile, File
2
+ from fastapi.responses import JSONResponse
3
+ import numpy as np
4
+ import cv2
5
+ import io
6
+ import base64
7
+ from mangum import Mangum
8
+
9
+ app = FastAPI()
10
+
11
+ # Including necessary functions (such as angle_between_vectors_degrees, calculate_angles, and order_points) here
12
+ def order_points(pts):
13
+ rect = np.zeros((4, 2), dtype="float32")
14
+ s = pts.sum(axis=1)
15
+ rect[0] = pts[np.argmin(s)]
16
+ rect[2] = pts[np.argmax(s)]
17
+ diff = np.diff(pts, axis=1)
18
+ rect[1] = pts[np.argmin(diff)]
19
+ rect[3] = pts[np.argmax(diff)]
20
+ return rect
21
+ # Function to calculate angle
22
+ def angle_between_vectors_degrees(u, v):
23
+ """Returns the angle in degrees between vectors 'u' and 'v'."""
24
+ cos_theta = np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v))
25
+ angle = np.arccos(np.clip(cos_theta, -1.0, 1.0))
26
+ return np.degrees(angle)
27
+
28
+ # Function to calculate angles of a contour
29
+ def calculate_angles(contour):
30
+ angles = []
31
+ # Ensure the contour is of size (4,1,2)
32
+ contour = contour.reshape((4, 2))
33
+ # Loop through each corner
34
+ for i in range(4):
35
+ # Calculate vectors
36
+ prev_vertex = contour[i - 1]
37
+ current_vertex = contour[i]
38
+ next_vertex = contour[(i + 1) % 4]
39
+
40
+ vector1 = prev_vertex - current_vertex
41
+ vector2 = next_vertex - current_vertex
42
+
43
+ angle = angle_between_vectors_degrees(vector1, vector2)
44
+ angles.append(angle)
45
+ return angles
46
+
47
+ @app.post("/process-receipts/")
48
+ async def process_receipts(file: UploadFile = File(...)):
49
+ if not file.content_type.startswith('image/'):
50
+ raise HTTPException(status_code=400, detail=f"File '{file.filename}' is not an image.")
51
+
52
+ try:
53
+ contents = await file.read()
54
+
55
+ # Convert the bytes to a NumPy array, then to an OpenCV image
56
+ nparr = np.frombuffer(contents, np.uint8)
57
+ cv_image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
58
+
59
+ ret, bw_image = cv2.threshold(cv_image, 127, 255, cv2.THRESH_BINARY)
60
+ blurred_bw_image = cv2.GaussianBlur(bw_image, (5, 5), 0)
61
+ edges = cv2.Canny(blurred_bw_image, 75, 150)
62
+ contours, hierarchy = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
63
+
64
+ base64_images = []
65
+ for contour in contours:
66
+ perimeter = cv2.arcLength(contour, True)
67
+ approximation = cv2.approxPolyDP(contour, 0.02 * perimeter, True)
68
+
69
+ if len(approximation) == 4:
70
+ x, y, w, h = cv2.boundingRect(approximation) # Get bounding box of approximation
71
+
72
+ # Proceed only if the bounding box is larger than 50px in both dimensions
73
+ if w > 100 and h > 100:
74
+ cropped_image = cv_image[y:y+h, x:x+w] # Cropped to bounding rectangle
75
+
76
+ _, encoded_img = cv2.imencode('.PNG', cropped_image)
77
+ base64_str = base64.b64encode(encoded_img).decode('utf-8')
78
+ base64_images.append(base64_str)
79
+
80
+ return JSONResponse(content={"receipt_images": base64_images})
81
+
82
+ except Exception as e:
83
+ raise HTTPException(status_code=500, detail=str(e))
84
+
85
+ finally:
86
+ await file.close()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ mangum
4
+ python-multipart
5
+ opencv-python-headless