Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
276 lines (219 loc) · 8.37 KB
/
Copy pathmain.py
File metadata and controls
276 lines (219 loc) · 8.37 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#main.py
from pathlib import Path
from io import BytesIO
from PIL import Image
from pydantic import BaseModel
from fastapi import FastAPI, UploadFile, HTTPException, BackgroundTasks, Response
from google.cloud import vision
from scan import get_candidate_urls, run_scan
from fastapi.middleware.cors import CORSMiddleware
import similarity
from database import SimilarArtwork, SessionLocal, Artwork
from storage import upload_blob, read_blob, delete_blob
from load_env import CORS_ORIGINS
from status import ArtworkScanStatus, SimilarArtworkStatus
app = FastAPI()
origins = CORS_ORIGINS
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
model, preprocess = similarity.load_clip_model()
vision_client = vision.ImageAnnotatorClient()
#TODO ORGANIZE THESE ENDPOINTS BETTERRRRR
class MatchStatusUpdate(BaseModel):
status: str
@app.patch("/matches/{match_id}")
async def update_match_status(match_id: int, update: MatchStatusUpdate):
if update.status not in [SimilarArtworkStatus.NEW, SimilarArtworkStatus.REVIEWED, SimilarArtworkStatus.DISMISSED]:
raise HTTPException(status_code=400, detail="Invalid status")
db = SessionLocal()
try:
match = db.query(SimilarArtwork).filter(SimilarArtwork.id == match_id).first()
if not match:
raise HTTPException(status_code=404, detail=f"No match found with id: {match_id}")
match.status = update.status
db.commit()
return {"id": match.id, "status": match.status}
finally:
db.close()
@app.post("/artworks")
async def register_artwork(user_id: str, file: UploadFile):
file_bytes = await file.read()
image = Image.open(BytesIO(file_bytes))
embedding = similarity.get_clip_embedding(model, preprocess, image)
embedding_bytes = similarity.embedding_to_bytes(embedding)
db = SessionLocal()
try:
artwork = Artwork(
user_id=user_id,
filename=file.filename,
filepath="",
embedding=embedding_bytes
)
db.add(artwork)
db.commit()
db.refresh(artwork)
extension = Path(file.filename).suffix or ".png"
file_path = f"artwork/{artwork.id}{extension}"
upload_blob(file_bytes, file_path)
artwork.filepath = str(file_path)
db.commit()
return {"id": artwork.id, "filename": artwork.filename}
finally:
db.close()
@app.get("/artworks")
async def get_artworks_list():
db = SessionLocal()
try:
artworks = db.query(Artwork).order_by(Artwork.id.desc()).all()
result = []
for a in artworks:
total = db.query(SimilarArtwork).filter(
SimilarArtwork.artwork_id == a.id,
SimilarArtwork.status != SimilarArtworkStatus.DISMISSED,
).count()
new_count = db.query(SimilarArtwork).filter(
SimilarArtwork.artwork_id == a.id,
SimilarArtwork.status == SimilarArtworkStatus.NEW,
).count()
result.append({
"id": a.id,
"filename": a.filename,
"user_id": a.user_id,
"time_uploaded": a.time_uploaded,
"match_count": total,
"new_match_count": new_count,
})
return result
finally:
db.close()
@app.get("/artworks/{artwork_id}")
async def get_artwork(artwork_id: int):
db = SessionLocal()
try:
artwork = db.query(Artwork).filter(Artwork.id == artwork_id).first()
if not artwork:
raise HTTPException(status_code=404, detail=f"No artwork found with id: {artwork_id}")
total = db.query(SimilarArtwork).filter(
SimilarArtwork.artwork_id == artwork.id,
SimilarArtwork.status != SimilarArtworkStatus.DISMISSED,
).count()
new_count = db.query(SimilarArtwork).filter(
SimilarArtwork.artwork_id == artwork.id,
SimilarArtwork.status == SimilarArtworkStatus.NEW,
).count()
return {
"id": artwork.id,
"filename": artwork.filename,
"user_id": artwork.user_id,
"time_uploaded": artwork.time_uploaded.isoformat(),
"match_count": total,
"new_match_count": new_count,
}
finally:
db.close()
@app.get("/artworks/{artwork_id}/image")
async def get_artwork_image(artwork_id: int):
db = SessionLocal()
try:
artwork = db.query(Artwork).filter(Artwork.id == artwork_id).first()
if not artwork:
raise HTTPException(status_code=404, detail=f"No artwork found with id: {artwork_id}")
image_bytes = read_blob(artwork.filepath)
image_extension = artwork.filepath.split(".")[-1]
return Response(content=image_bytes, media_type=f"image/{image_extension}")
finally:
db.close()
@app.delete("/artworks/{artwork_id}")
async def delete_artwork(artwork_id: int):
db = SessionLocal()
try:
artwork = db.query(Artwork).filter(Artwork.id == artwork_id).first()
if not artwork:
raise HTTPException(status_code=404, detail=f"No artwork found with id: {artwork_id}")
# Delete associated matches first
db.query(SimilarArtwork).filter(SimilarArtwork.artwork_id == artwork_id).delete()
# Delete the artwork
db.delete(artwork)
db.commit()
delete_blob(artwork.filepath)
return {"id": artwork_id, "status": "deleted"}
finally:
db.close()
# @app.post("/artworks/{artwork_id}/compare")
# async def compare_with_artwork(artwork_id: int, file: UploadFile):
# db = SessionLocal()
# try:
# artwork = db.query(Artwork).filter(Artwork.id == artwork_id).first()
# if not artwork:
# raise HTTPException(status_code=404, detail=f"No artwork found with id: {artwork_id}")
# uploaded_image = Image.open(BytesIO(await file.read()))
# stored_image = Image.open(artwork.filepath)
# is_similar, similarity_score = similarity.compare_images(
# uploaded_image, stored_image, model, preprocess
# )
# return {
# "artwork_id": artwork_id,
# "artwork_filename": artwork.filename,
# "is_similar": is_similar,
# "similarity_score": similarity_score
# }
# finally:
# db.close()
@app.post("/artworks/{artwork_id}/scan")
async def scan_artwork(artwork_id: int, background_tasks: BackgroundTasks):
db = SessionLocal()
try:
artwork = db.query(Artwork).filter(Artwork.id == artwork_id).first()
if not artwork:
raise HTTPException(status_code=404, detail=f"No artwork found with id: {artwork_id}")
content = read_blob(artwork.filepath)
candidate_urls = get_candidate_urls(vision_client, content)
background_tasks.add_task(run_scan, artwork_id, candidate_urls, artwork.filepath, model, preprocess)
return {"artwork_id": artwork_id, "status": "scan_started", "candidate_count": len(candidate_urls)}
finally:
db.close()
@app.get("/artworks/{artwork_id}/scan")
async def get_scan_results(artwork_id: int):
db = SessionLocal()
try:
results = (
db.query(SimilarArtwork)
.filter(
SimilarArtwork.artwork_id == artwork_id,
SimilarArtwork.status != SimilarArtworkStatus.DISMISSED,
)
.order_by(SimilarArtwork.similarity_score.desc())
.all()
)
return {
"artwork_id": artwork_id,
"matches": [
{
"id": r.id,
"url": r.url,
"similarity_score": r.similarity_score,
"time_scanned": r.time_scanned.isoformat(),
"status": r.status,
}
for r in results
],
}
finally:
db.close()
@app.post("/artworks/{artwork_id}/mark-reviewed")
async def mark_matches_reviewed(artwork_id: int):
db = SessionLocal()
try:
db.query(SimilarArtwork).filter(
SimilarArtwork.artwork_id == artwork_id,
SimilarArtwork.status == SimilarArtworkStatus.NEW,
).update({"status": "reviewed"})
db.commit()
return {"artwork_id": artwork_id, "status": "ok"}
finally:
db.close()