dal4933 commited on
Commit
7129810
·
verified ·
1 Parent(s): 38bfe3c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -57
app.py CHANGED
@@ -1,75 +1,104 @@
1
- # app.py
 
 
2
  import cv2
3
  import zxingcpp
4
- import gradio as gr
5
  import numpy as np
6
  from PIL import Image
7
  import base64
8
  import io
 
9
 
10
- def scan_barcode(image):
11
- """Scan barcode from image"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  try:
13
- # Handle different input types
14
- if isinstance(image, str):
15
- # If it's a base64 string, decode it
16
- if image.startswith('data:image'):
17
- # Remove the data:image/jpeg;base64, prefix
18
- image_data = image.split(',')[1]
19
- image_bytes = base64.b64decode(image_data)
20
- pil_image = Image.open(io.BytesIO(image_bytes))
21
- image = np.array(pil_image)
22
 
23
- # Ensure image is numpy array
24
- if not isinstance(image, np.ndarray):
25
- return {"status": "error", "message": "Invalid image format"}
26
 
27
- # Convert RGB to BGR for OpenCV if needed
28
- if len(image.shape) == 3 and image.shape[2] == 3:
29
- bgr_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
30
- else:
31
- bgr_image = image
32
 
33
- # Scan barcodes
34
- results = zxingcpp.read_barcodes(bgr_image)
35
-
36
- if results:
37
- # Return first barcode found
38
- return {
39
- "status": "success",
40
- "text": results[0].text,
41
- "format": str(results[0].format)
42
- }
43
-
44
- return {"status": "error", "message": "No barcode detected"}
45
 
 
 
46
  except Exception as e:
47
- return {"status": "error", "message": f"Processing error: {str(e)}"}
48
 
49
- # Create Gradio app using Blocks for better API control
50
- app = gr.Blocks()
 
51
 
52
- with app:
53
- gr.Markdown("# 📦 Barcode Scanner API")
54
-
55
- # Define the interface components
56
- image_input = gr.Image(label="Upload Image", type="numpy")
57
- scan_button = gr.Button("Scan Barcode", variant="primary")
58
- result_output = gr.JSON(label="Scan Result")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- # Connect the function
61
- scan_button.click(
62
- fn=scan_barcode,
63
- inputs=image_input,
64
- outputs=result_output,
65
- api_name="scan"
66
- )
67
 
68
- # Launch the application
69
  if __name__ == "__main__":
70
- app.launch(
71
- server_name="0.0.0.0",
72
- server_port=7860,
73
- show_error=True,
74
- share=False
75
- )
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
  import cv2
5
  import zxingcpp
 
6
  import numpy as np
7
  from PIL import Image
8
  import base64
9
  import io
10
+ from typing import Dict, Any
11
 
12
+ app = FastAPI(title="Barcode Scanner API", version="1.0.0")
13
+
14
+ # Add CORS middleware
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"], # In production, specify your frontend domain
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
+
23
+ class ImageRequest(BaseModel):
24
+ image: str # Base64 encoded image
25
+
26
+ class ScanResponse(BaseModel):
27
+ status: str
28
+ text: str = None
29
+ format: str = None
30
+ message: str = None
31
+
32
+ def decode_base64_image(base64_string: str) -> np.ndarray:
33
+ """Decode base64 image to numpy array"""
34
  try:
35
+ # Handle data URI format
36
+ if base64_string.startswith('data:image'):
37
+ # Remove the data:image/jpeg;base64, prefix
38
+ base64_string = base64_string.split(',')[1]
 
 
 
 
 
39
 
40
+ # Decode base64
41
+ image_bytes = base64.b64decode(base64_string)
 
42
 
43
+ # Convert to PIL Image
44
+ pil_image = Image.open(io.BytesIO(image_bytes))
 
 
 
45
 
46
+ # Convert to numpy array
47
+ image_array = np.array(pil_image)
 
 
 
 
 
 
 
 
 
 
48
 
49
+ return image_array
50
+
51
  except Exception as e:
52
+ raise HTTPException(status_code=400, detail=f"Invalid image format: {str(e)}")
53
 
54
+ @app.get("/")
55
+ async def root():
56
+ return {"message": "Barcode Scanner API is running!"}
57
 
58
+ @app.get("/health")
59
+ async def health_check():
60
+ return {"status": "healthy"}
61
+
62
+ @app.post("/scan", response_model=ScanResponse)
63
+ async def scan_barcode(request: ImageRequest):
64
+ """Scan barcode from base64 encoded image"""
65
+ try:
66
+ # Decode the base64 image
67
+ image_array = decode_base64_image(request.image)
68
+
69
+ # Convert RGB to BGR for OpenCV (if needed)
70
+ if len(image_array.shape) == 3 and image_array.shape[2] == 3:
71
+ bgr_image = cv2.cvtColor(image_array, cv2.COLOR_RGB2BGR)
72
+ elif len(image_array.shape) == 3 and image_array.shape[2] == 4:
73
+ # Handle RGBA images
74
+ rgb_image = cv2.cvtColor(image_array, cv2.COLOR_RGBA2RGB)
75
+ bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
76
+ else:
77
+ bgr_image = image_array
78
+
79
+ # Scan for barcodes
80
+ results = zxingcpp.read_barcodes(bgr_image)
81
+
82
+ if results:
83
+ # Return the first barcode found
84
+ barcode = results[0]
85
+ return ScanResponse(
86
+ status="success",
87
+ text=barcode.text,
88
+ format=str(barcode.format)
89
+ )
90
+ else:
91
+ return ScanResponse(
92
+ status="error",
93
+ message="No barcode detected"
94
+ )
95
 
96
+ except HTTPException:
97
+ raise
98
+ except Exception as e:
99
+ raise HTTPException(status_code=500, detail=f"Processing error: {str(e)}")
 
 
 
100
 
101
+ # For HuggingFace Spaces, you might need this
102
  if __name__ == "__main__":
103
+ import uvicorn
104
+ uvicorn.run(app, host="0.0.0.0", port=7860)