Saad0KH commited on
Commit
4e54f0a
·
verified ·
1 Parent(s): 670a735

Rename app.py to chromedb_service.py

Browse files
Files changed (2) hide show
  1. app.py +0 -78
  2. chromedb_service.py +87 -0
app.py DELETED
@@ -1,78 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- from __future__ import annotations
4
-
5
- import cv2
6
- import gradio as gr
7
- import huggingface_hub
8
- import insightface
9
- import numpy as np
10
- import onnxruntime as ort
11
- from PIL import Image
12
-
13
- TITLE = "insightface Person Detection"
14
- DESCRIPTION = "https://github.com/deepinsight/insightface/tree/master/examples/person_detection"
15
-
16
- def load_model():
17
- path = huggingface_hub.hf_hub_download("public-data/insightface", "models/scrfd_person_2.5g.onnx")
18
- options = ort.SessionOptions()
19
- options.intra_op_num_threads = 8
20
- options.inter_op_num_threads = 8
21
- session = ort.InferenceSession(
22
- path, sess_options=options, providers=["CPUExecutionProvider", "CUDAExecutionProvider"]
23
- )
24
- model = insightface.model_zoo.retinaface.RetinaFace(model_file=path, session=session)
25
- return model
26
-
27
- def detect_person(
28
- img: np.ndarray, detector: insightface.model_zoo.retinaface.RetinaFace
29
- ) -> tuple[np.ndarray, np.ndarray]:
30
- bboxes, kpss = detector.detect(img)
31
- bboxes = np.round(bboxes[:, :4]).astype(int)
32
- kpss = np.round(kpss).astype(int)
33
- kpss[:, :, 0] = np.clip(kpss[:, :, 0], 0, img.shape[1])
34
- kpss[:, :, 1] = np.clip(kpss[:, :, 1], 0, img.shape[0])
35
- vbboxes = bboxes.copy()
36
- vbboxes[:, 0] = kpss[:, 0, 0]
37
- vbboxes[:, 1] = kpss[:, 0, 1]
38
- vbboxes[:, 2] = kpss[:, 4, 0]
39
- vbboxes[:, 3] = kpss[:, 4, 1]
40
- return bboxes, vbboxes
41
-
42
- def visualize(image: np.ndarray, bboxes: np.ndarray, vbboxes: np.ndarray) -> list[np.ndarray]:
43
- person_images = []
44
- for i in range(bboxes.shape[0]):
45
- bbox = bboxes[i]
46
- x1, y1, x2, y2 = bbox
47
- person_img = image[y1:y2, x1:x2]
48
-
49
- # Convert numpy array to PIL Image and append
50
- pil_img = Image.fromarray(person_img)
51
- person_images.append(pil_img)
52
-
53
- return person_images
54
-
55
- detector = load_model()
56
- detector.prepare(-1, nms_thresh=0.5, input_size=(640, 640))
57
-
58
- def detect(image: np.ndarray) -> list[np.ndarray]:
59
- if image is None:
60
- return []
61
-
62
- image = image[:, :, ::-1] # RGB -> BGR
63
- bboxes, vbboxes = detect_person(image, detector)
64
- person_images = visualize(image, bboxes, vbboxes)
65
-
66
- # Convert PIL images to numpy arrays and return
67
- return [np.array(img) for img in person_images]
68
-
69
- demo = gr.Interface(
70
- fn=detect,
71
- inputs=gr.Image(label="Input", type="numpy"),
72
- outputs=gr.Gallery(label="Detected Persons"),
73
- title=TITLE,
74
- description=DESCRIPTION,
75
- )
76
-
77
- if __name__ == "__main__":
78
- demo.queue(max_size=10).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
chromedb_service.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from PIL import Image
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ import chromadb
6
+ from chromadb.config import Settings
7
+
8
+ # Fonction pour télécharger une image depuis une URL
9
+ def download_image(url):
10
+ response = requests.get(url)
11
+ if response.status_code != 200:
12
+ raise Exception(f"Erreur lors du téléchargement de l'image : {response.status_code}")
13
+ return Image.open(io.BytesIO(response.content))
14
+
15
+ # Fonction pour encoder une image en vecteurs à partir d'une URL
16
+ def encode_image_from_url(image_url):
17
+ image = download_image(image_url)
18
+ image = image.resize((224, 224)) # Redimensionner à 224x224
19
+ image_array = np.array(image) / 255.0 # Normaliser les valeurs des pixels
20
+ image_tensor = tf.convert_to_tensor(image_array, dtype=tf.float32)
21
+ image_tensor = tf.expand_dims(image_tensor, axis=0) # Ajouter une dimension pour le batch
22
+
23
+ # Charger le modèle MobileNet
24
+ model = tf.keras.applications.MobileNetV2(weights='imagenet', include_top=False, pooling='avg')
25
+ embeddings = model(image_tensor)
26
+ return embeddings.numpy()[0] # Retourner les vecteurs sous forme de tableau
27
+
28
+ # Ajouter une image dans ChromaDB
29
+ def add_image_to_chroma(collection_name, id, image_url, metadata):
30
+ vector = encode_image_from_url(image_url)
31
+ chroma_client = chromadb.Client(Settings(path="https://stable-diffusion-engine.oneiro-lego.com"))
32
+ collection = chroma_client.get_or_create_collection(
33
+ name=collection_name, dimension=len(vector)
34
+ )
35
+ collection.add(
36
+ ids=[id],
37
+ embeddings=[vector],
38
+ metadatas=[metadata]
39
+ )
40
+ print(f"Image {image_url} ajoutée avec succès !")
41
+
42
+ # Ajouter un document dans ChromaDB
43
+ def add_document(collection_name, id, text, metadata):
44
+ chroma_client = chromadb.Client(Settings(path="https://stable-diffusion-engine.oneiro-lego.com"))
45
+ collection = chroma_client.get_or_create_collection(name=collection_name)
46
+ collection.upsert(
47
+ documents=[text],
48
+ ids=[id],
49
+ metadatas=[metadata]
50
+ )
51
+ print(f"Document {id} ajouté avec succès !")
52
+
53
+ # Supprimer un document dans ChromaDB
54
+ def delete_document(collection_name, id):
55
+ chroma_client = chromadb.Client(Settings(path="https://stable-diffusion-engine.oneiro-lego.com"))
56
+ collection = chroma_client.get_or_create_collection(name=collection_name)
57
+ collection.delete(ids=[id])
58
+ print(f"Document {id} supprimé avec succès !")
59
+
60
+ # Supprimer une collection dans ChromaDB
61
+ def delete_collection(collection_name):
62
+ chroma_client = chromadb.Client(Settings(path="https://stable-diffusion-engine.oneiro-lego.com"))
63
+ chroma_client.delete_collection(name=collection_name)
64
+ print(f"Collection {collection_name} supprimée avec succès !")
65
+
66
+ # Recherche dans une collection
67
+ def search(collection_name, query, n_results):
68
+ chroma_client = chromadb.Client(Settings(path="https://stable-diffusion-engine.oneiro-lego.com"))
69
+ collection = chroma_client.get_or_create_collection(name=collection_name)
70
+ results = collection.query(
71
+ query_texts=[query],
72
+ n_results=n_results
73
+ )
74
+ return parse_chromadb_response(results)
75
+
76
+ # Analyse des réponses de ChromaDB
77
+ def parse_chromadb_response(response):
78
+ results = [
79
+ {
80
+ "id": response["ids"][0][i],
81
+ "distance": response["distances"][0][i],
82
+ "document": response["documents"][0][i],
83
+ "metadata": response["metadatas"][0].get(i)
84
+ }
85
+ for i in range(len(response["ids"][0]))
86
+ ]
87
+ return results