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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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import os
from flask import Flask,request,jsonify,make_response
from flask_bcrypt import Bcrypt
from functools import wraps
from supabase import create_client
from flask_jwt_extended import JWTManager, create_access_token,unset_jwt_cookies, jwt_required, get_jwt_identity,decode_token
from App.models import  User,LostItem,FoundItem,Match
from flask_cors import CORS
from src.training import encode_img_and_text
from qdrant_client import QdrantClient
from qdrant_client.http import models
import cloudinary
from cloudinary import uploader 
import warnings
import base64
from io import BytesIO
import threading
from datetime import timedelta
import json
# from dotenv import load_dotenv
# load_dotenv()
warnings.filterwarnings("ignore", message=".*QuickGELU mismatch.*")



app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
app.config["JWT_SECRET_KEY"] = os.getenv("JWT_SECRET_KEY")
app.config["JWT_TOKEN_LOCATION"] = ["cookies"]
app.config["JWT_ACCESS_COOKIE_NAME"] = "Token"
app.config["JWT_COOKIE_SAMESITE"] = "None"
app.config["JWT_COOKIE_SECURE"] = False
app.config["JWT_COOKIE_DOMAIN"] = ".localhost"
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(days=3)


qdrant=QdrantClient(
    url=os.getenv("Qdrant_url"),
    api_key=os.getenv("Qdrant_api_key"),
)

cloudinary.config(
    cloud_name=os.getenv("CLOUDINARY_CLIENT_NAME"),
    api_key=os.getenv("CLOUDINARY_API_KEY"),
    api_secret=os.getenv("CLOUDINARY_API_SECRET"),
)


db = create_client(os.getenv("DATABASE_URL"),os.getenv("SUPABASE_KEY"))
bcrypt=Bcrypt(app)
jwt=JWTManager(app)
CORS(app, supports_credentials=True, origins=[os.getenv("CLIENT")])


print('Qdrant connected')
print("Posgres Connected")



def decode_jwt(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        token=request.cookies.get("Token")
        if not token:
            print('no token found')
            return jsonify({
                "message":"No Token Found"
            })
        else:
            id=decode_token(token)["sub"]
            return fn(user_id=id, *args, **kwargs)
    return wrapper

class DotDict(dict):
    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(f"No such attribute: {key}")

    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__



    

def upload_img(img):
    return uploader.upload(img, resource_type="image")["secure_url"]

@app.route("/", methods=["GET"])
def root():
    return {
        "status": "ok",
        "service": "Findr backend",
        "message": "API is running"
    }, 200  


@app.route('/register',methods=["POST"])
def register():
    try:
        print("received")
        data=request.get_json()
        first_name=data['firstName']
        last_name=data['lastName']
        email=data['email']
        phone=data['phone']
        password=data['password']
        if db.table("users").select("*").eq("email",email).limit(1).execute().data:

            return jsonify({
                "success":False,
                "message":"User Already Exist"
            })
        hashing=bcrypt.generate_password_hash(password).decode("utf-8")
        new_user=db.table("users").insert({"first_name":first_name,"last_name":last_name,"email":email,"phone":phone,"password":hashing}).execute().data[0]
        
        token=create_access_token(identity=str(new_user.get("id")), expires_delta=timedelta(days=3))
        res=make_response({
            "success":True,
            "message":"User Registered Successfully",

        })
        res.set_cookie("Token",token,httponly=True,secure=True,samesite="None",max_age=259200,domain=".localhost")
        return res,200
    except Exception as e:
        print(e)
        return jsonify({
                "sucsess":False,
                "message":"Internal Server Error"
            }),400

@app.route("/login",methods=["POST"])
def login():
    try:
        data=request.get_json()
        print(data)
        email=data['email']
        password=data['password']
        user= db.table("users").select("*").eq("email",email).limit(1).execute().data[0]
        if not user or not bcrypt.check_password_hash(user.get("password"),password):
            return jsonify({
                "sucsess":False,
                "message":"No User Found"
            }),200
        token=create_access_token(identity=str(user.get("id")), expires_delta=timedelta(days=3))
        res=make_response({
            "success":True,
            "message":"User Login Successfully",

            })
        res.set_cookie("Token",token,httponly=True,secure=True,samesite="None",max_age=259200,domain=".localhost")
        return res,200
    except Exception as e:
        print(e)
        return jsonify({
                "sucsess":False,
                "message":"Internal Server Error"
            }),400


@app.route('/logout',methods=["GET"])
def logout():
    res=make_response({
        "success":True,
        "message":"Logout Successfully"
    })
    unset_jwt_cookies(res)
    return res,200

@app.route('/get_user',methods=['GET'])
@decode_jwt
def get_user(user_id):
    user=user= db.table("users").select("*").eq("id",user_id).limit(1).execute().data[0]
    return jsonify({
        "success":True,
        "user":{"first_name": user.get("first_name"),
                "last_name": user.get("last_name"),
                "email": user.get("email"),
                "phone_number": user.get("phone")}
            }), 200


@app.route('/lostItem',methods=['POST'])
@decode_jwt
def lostItem(user_id):
    print('search start')
    try:
        imgs_data=request.files.getlist('item')
        img_urls=[upload_img(img) for img in imgs_data]    
        description=request.form.get('description')
        print(imgs_data, description)
        vector=encode_img_and_text(imgs_data,description)
        lastSeenLocation=request.form.get('lastSeenLocation')
        dateTimeLost=request.form.get('dateTimeLost')
        name=request.form.get('name')
        email=request.form.get('email')
        phone=request.form.get('phone')
        reward=request.form.get('reward')
        additionalNotes=request.form.get('additionalNotes')
        item=db.table("lostItem").insert({"user_id":user_id,"name":name,"email":email,"phone":phone,"description":description,"lastSeenLocation":lastSeenLocation,"dateTimeLost":dateTimeLost,"reward":reward,"additionalNotes":additionalNotes,"image_url": img_urls}).execute().data[0]
        print('db save', len(vector))

        collections = qdrant.get_collections().collections
        existing_names = [c.name for c in collections]
    
        if "lost_items" not in existing_names:
            qdrant.create_collection(
            collection_name="lost_items",
            vectors_config=models.VectorParams(
                size=512,
                distance=models.Distance.COSINE
            )
        )

        qdrant.upsert(
            collection_name="lost_items",
            points=[
                models.PointStruct(id=item.get("id"), vector=vector, payload={"description":description,"place_lost":lastSeenLocation,"status" : "active"})
            ],
        )
        print('vector save')
        return jsonify({
            "success":True
        }),200
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success":False
        }),400


@app.route('/foundItem',methods=['POST'])
@decode_jwt
def foundItem(user_id):
    print('search start')
    try:
        imgs_data=request.files.getlist('item')
        img_urls=[upload_img(img) for img in imgs_data]    
        description=request.form.get('description')
        print(imgs_data, description)
        vector=encode_img_and_text(imgs_data,description)
        found_near=request.form.get('found_near')
        name=request.form.get('name')
        email=request.form.get('email')
        phone=request.form.get('phone')
        item=db.table("foundItem").insert({"user_id":user_id,"name":name,"email":email,"phone":phone,"description":description,"found_near":found_near,"image_url": img_urls}).execute().data[0]

        print('db save', len(vector))

        collections = qdrant.get_collections().collections
        existing_names = [c.name for c in collections]
    
        if "found_items" not in existing_names:
            qdrant.create_collection(
            collection_name="found_items",
            vectors_config=models.VectorParams(
                size=512,
                distance=models.Distance.COSINE
            )
        )

        qdrant.upsert(
            collection_name="found_items",
            points=[
                models.PointStruct(id=item.get("id"), vector=vector, payload={"description":description,"place_found":found_near,"status" : "active"})
            ],
        )
        print('vector save')
        return jsonify({
            "success":True
        }),200
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            "success":False
        }),200

@app.route('/allLostItems',methods=['GET'])
@decode_jwt
def allLostItems(user_id):
    
        items = db.table("lostItem").select("*").eq("user_id",user_id).execute().data
        output = []
        for item in items:
            output.append({
            "id": item.get("id"),
            "name": item.get("name"),
            "email": item.get("email"),
            "phone": item.get("phone"),
            "description": item.get("description"),
            "lastSeenLocation": item.get("lastSeenLocation"),
            "dateTimeLost": item.get("dateTimeLost"),
            "reward": item.get("reward"),
            "additionalNotes": item.get("additionalNotes"),
            "image_url": item.get("image_url"),
            "status": item.get("status"),
            "created_at": item.get("created_at")
        })
        return jsonify({
            "success":True,
            "lostItems":output
        }),200

@app.route('/matchLost/<lost_id>',methods=['GET'])
def matchLost(lost_id):
    items = db.table("lostItem").select("*").eq("id",lost_id).limit(1).execute().data[0]
    found_items=[]
    if not items.get("found_items"):
        return jsonify({
            "success":False,
            "message":"No Lost Item Found"
        }),400
    for ids in items.get("found_items"):
        found_item=db.table("foundItem").select("*").eq("id",int(ids)).limit(1).execute().data[0]
        if found_item:
            found_items.append({
                "id": found_item.get("id"),
                "name": found_item.get("name"),
                "email": found_item.get("email"),
                "phone": found_item.get("phone"),
                "description": found_item.get("description"),
                "found_near": found_item.get("found_near"),
                "image_url": found_item.get("image_url"),
                "status": found_item.get("status"),
                "created_at": found_item.get("created_at")
            })   
    
    return jsonify({
            "success":True,
            "foundItems": found_items
        }),200



@app.route('/matchFound/<lost_id>',methods=['GET'])
def matchFound(lost_id):
    items = db.table("foundItem").select("*").eq("id",lost_id).limit(1).execute().data[0]

    found_items=[]
    if not items.get("lost_items"):
        return jsonify({
            "success":False,
            "message":"No Found Item Found"
        }),200
    for ids in items.get("lost_items"):
        found_item=db.table("lostItem").select("*").eq("id",int(ids)).limit(1).execute().data[0]
        if found_item:
            found_items.append({
                "id": found_item.get("id"),
                "name": found_item.get("name"),
                "email": found_item.get("email"),
                "phone": found_item.get("phone"),
                "description": found_item.get("description"),
                "found_near": found_item.get("lastSeenLocation"),
                "image_url": found_item.get("image_url"),
                "status": found_item.get("status"),
                "created_at": found_item.get("created_at")
            })
    
    return jsonify({
            "success":True,
            "foundItems": found_items
        }),200


@app.route('/lostMatchDetail/<lost_id>',methods=['GET'])
def lostMatchDetail(lost_id):
    found_item = db.table("lostItem").select("*").eq("id",lost_id).limit(1).execute().data[0]
    found_items=[]
    if not found_item:
        return jsonify({
            "success":False,
            "message":"No Found Item Found"
        }),400
    
    found_items.append({
                "id": found_item.get("id"),
                "name": found_item.get("name"),
                "email": found_item.get("email"),
                "phone": found_item.get("phone"),
                "description": found_item.get("description"),
                "found_near": found_item.get("lastSeenLocation"),
                "image_url": found_item.get("image_url"),
                "status": found_item.get("status"),
                "date_lost":found_item.get("dateTimeLost"),
                "reward":found_item.get("reward"),
                "additional_notes":found_item.get("additionalNotes"),
                "created_at": found_item.get("created_at")
    })

    
    return jsonify({
            "success":True,
            "foundItems": found_items
        }),200


@app.route('/allFoundItems',methods=['GET'])
@decode_jwt
def allFoundItems(user_id):
    items = db.table("foundItem").select("*").eq("user_id",user_id).execute().data
    output = []
    for item in items:
            output.append({
            "id": item.get("id"),
            "name": item.get("name"),
            "email": item.get("email"),
            "phone": item.get("phone"),
            "description": item.get("description"),
            "found_near": item.get("found_near"),
            "image_url": item.get("image_url"),
            "status": item.get("status"),
            "created_at": item.get("created_at")
        })
    return jsonify({
            "success":True,
            "foundItems":output
        }),200

@app.route('/foundMatchDetail/<lost_id>',methods=['GET'])
def foundMatchDetail(lost_id):
    found_item = db.table("foundItem").select("*").eq("id",lost_id).limit(1).execute().data[0]
    
    found_items=[]
    if not found_item:
        return jsonify({
            "success":False,
            "message":"No Found Item Found"
        }),400
    
    found_items.append({
                "id": found_item.get("id"),
                "name": found_item.get("name"),
                "email": found_item.get("email"),
                "phone": found_item.get("phone"),
                "description": found_item.get("description"),
                "found_near": found_item.get("found_near"),
                "image_url": found_item.get("image_url"),
                "status": found_item.get("status"),
                "created_at": found_item.get("created_at")
    })
    
    
    return jsonify({
            "success":True,
            "foundItems": found_items
        }),200
    
if __name__ == "__main__":
    app.run(
        host="0.0.0.0",
        port=7860,
        debug=False,
        use_reloader=False
    )