-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend.py
79 lines (65 loc) · 2.35 KB
/
backend.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from flask import Flask, request, jsonify
import os
import sqlite3
from PIL import Image
import pytesseract
import requests
import datetime
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
DB_FILE = 'tag_keeper.db'
# Ensure the upload folder exists
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
# Initialize SQLite database
def init_db():
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
extracted_text TEXT,
image_path TEXT,
timestamp TEXT
)
''')
conn.commit()
# Process image and extract text
def process_image(image_path):
image = Image.open(image_path)
image = image.convert('L')
text = pytesseract.image_to_string(image)
return text.strip()
# Store extracted data into SQLite
def store_tag_data(text, image_path):
timestamp = datetime.datetime.now().isoformat()
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute("INSERT INTO tags (extracted_text, image_path, timestamp) VALUES (?, ?, ?)",
(text, image_path, timestamp))
conn.commit()
return cursor.lastrowid
@app.route('/upload', methods=['POST'])
def upload_image():
if 'image' not in request.files:
return jsonify({"error": "No image provided"}), 400
file = request.files['image']
if file.filename == '':
return jsonify({"error": "No file selected"}), 400
filepath = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(filepath)
# Process the image using OCR
tag_text = process_image(filepath)
# Store data in SQLite
tag_id = store_tag_data(tag_text, filepath)
return jsonify({"tag_id": tag_id, "tag_text": tag_text, "image_path": filepath})
@app.route('/tags', methods=['GET'])
def get_tags():
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute("SELECT id, extracted_text, image_path, timestamp FROM tags ORDER BY timestamp DESC")
tags = cursor.fetchall()
return jsonify([{ "id": row[0], "extracted_text": row[1], "image_path": row[2], "timestamp": row[3] } for row in tags])
if __name__ == '__main__':
init_db()
app.run(debug=True)