Skip to content

Commit 54c7a41

Browse files
committed
Create backend.py
1 parent a4149df commit 54c7a41

File tree

1 file changed

+180
-0
lines changed

1 file changed

+180
-0
lines changed

examples/official/fastapi/backend.py

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
# backend.py
2+
from fastapi import FastAPI, File, UploadFile, Form
3+
from fastapi.responses import HTMLResponse, JSONResponse
4+
from fastapi.staticfiles import StaticFiles
5+
from fastapi.middleware.cors import CORSMiddleware
6+
from dynamsoft_capture_vision_bundle import *
7+
import io
8+
import os
9+
10+
app = FastAPI()
11+
12+
# Initialize Dynamsoft components
13+
license_key = "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ=="
14+
error_code, error_message = LicenseManager.init_license(license_key)
15+
cvr_instance = CaptureVisionRouter()
16+
17+
# Configure CORS
18+
app.add_middleware(
19+
CORSMiddleware,
20+
allow_origins=["*"],
21+
allow_methods=["*"],
22+
allow_headers=["*"],
23+
)
24+
25+
# Mount static files
26+
# app.mount("/static", StaticFiles(directory="static"), name="static")
27+
28+
@app.get("/", response_class=HTMLResponse)
29+
async def upload_page():
30+
return """
31+
<!DOCTYPE html>
32+
<html>
33+
<head>
34+
<title>Barcode Scanner</title>
35+
<style>
36+
.container { max-width: 600px; margin: 2rem auto; padding: 2rem; }
37+
.preview { max-width: 300px; margin: 1rem 0; }
38+
.progress { display: none; color: blue; }
39+
</style>
40+
</head>
41+
<body>
42+
<div class="container">
43+
<h1>Upload Barcode Image</h1>
44+
<input type="file" id="fileInput" accept="image/*" capture="camera">
45+
<img class="preview" id="preview">
46+
<div class="progress" id="progress">Processing...</div>
47+
<div id="result"></div>
48+
49+
<script>
50+
const fileInput = document.getElementById('fileInput');
51+
const preview = document.getElementById('preview');
52+
const progress = document.getElementById('progress');
53+
const resultDiv = document.getElementById('result');
54+
55+
fileInput.addEventListener('change', async (e) => {
56+
const file = e.target.files[0];
57+
if (!file) return;
58+
59+
// Display preview
60+
preview.src = URL.createObjectURL(file);
61+
preview.style.display = 'block';
62+
63+
// Show progress
64+
progress.style.display = 'block';
65+
66+
const formData = new FormData();
67+
formData.append('file', file);
68+
69+
try {
70+
const response = await fetch('/scan', {
71+
method: 'POST',
72+
body: formData
73+
});
74+
75+
const data = await response.json();
76+
if (data.success) {
77+
let resultHTML = `
78+
<h3>Found ${data.count} barcode(s)</h3>
79+
<div class="results-container">
80+
`;
81+
82+
data.items.forEach((item, index) => {
83+
resultHTML += `
84+
<div class="barcode-result">
85+
<h4>Barcode #${index + 1}</h4>
86+
<p><strong>Type:</strong> ${item.format}</p>
87+
<p><strong>Content:</strong> ${item.text}</p>
88+
<div class="location">
89+
<span>Coordinates:</span>
90+
<ul>
91+
<li>Point 1: (${item.location.x1}, ${item.location.y1})</li>
92+
<li>Point 2: (${item.location.x2}, ${item.location.y2})</li>
93+
<li>Point 3: (${item.location.x3}, ${item.location.y3})</li>
94+
<li>Point 4: (${item.location.x4}, ${item.location.y4})</li>
95+
</ul>
96+
</div>
97+
</div>
98+
`;
99+
});
100+
101+
resultHTML += `</div>`;
102+
resultDiv.innerHTML = resultHTML;
103+
} else {
104+
resultDiv.innerHTML = `Error: ${data.error}`;
105+
}
106+
} catch (err) {
107+
resultDiv.innerHTML = 'Request failed';
108+
} finally {
109+
progress.style.display = 'none';
110+
}
111+
});
112+
</script>
113+
</div>
114+
</body>
115+
</html>
116+
"""
117+
118+
@app.post("/scan")
119+
async def scan_barcode(file: UploadFile = File(...)):
120+
try:
121+
# Read image file
122+
image_data = await file.read()
123+
124+
# # Decode barcodes
125+
result = cvr_instance.capture(image_data, EnumPresetTemplate.PT_READ_BARCODES.value)
126+
127+
if result.get_error_code() != EnumErrorCode.EC_OK:
128+
return JSONResponse(
129+
{"success": False, "error": "No barcode detected"},
130+
status_code=400
131+
)
132+
133+
# Get and return results
134+
items = result.get_items()
135+
return_items = []
136+
for item in items:
137+
format_type = item.get_format()
138+
text = item.get_text()
139+
140+
location = item.get_location()
141+
x1 = location.points[0].x
142+
y1 = location.points[0].y
143+
x2 = location.points[1].x
144+
y2 = location.points[1].y
145+
x3 = location.points[2].x
146+
y3 = location.points[2].y
147+
x4 = location.points[3].x
148+
y4 = location.points[3].y
149+
del location
150+
151+
return_items.append({
152+
"format": format_type,
153+
"text": text,
154+
"location": {
155+
"x1": x1,
156+
"y1": y1,
157+
"x2": x2,
158+
"y2": y2,
159+
"x3": x3,
160+
"y3": y3,
161+
"x4": x4,
162+
"y4": y4
163+
}
164+
})
165+
166+
return {
167+
"success": True,
168+
"count": len(items),
169+
"items": return_items
170+
}
171+
172+
except Exception as e:
173+
return JSONResponse(
174+
{"success": False, "error": str(e)},
175+
status_code=500
176+
)
177+
178+
if __name__ == "__main__":
179+
import uvicorn
180+
uvicorn.run(app, host="0.0.0.0", port=8000)

0 commit comments

Comments
 (0)