davidtran999 commited on
Commit
c7864e0
·
verified ·
1 Parent(s): 1463e3d

Upload backend/hue_portal/core/embedding_utils.py with huggingface_hub

Browse files
backend/hue_portal/core/embedding_utils.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for loading and working with stored embeddings.
3
+ """
4
+ import pickle
5
+ from typing import Optional
6
+ import numpy as np
7
+ from django.db import models
8
+
9
+
10
+ def save_embedding(instance: models.Model, embedding: np.ndarray) -> bool:
11
+ """
12
+ Save embedding to model instance.
13
+
14
+ Args:
15
+ instance: Django model instance.
16
+ embedding: Numpy array of embedding.
17
+
18
+ Returns:
19
+ True if successful, False otherwise.
20
+ """
21
+ if embedding is None:
22
+ return False
23
+
24
+ try:
25
+ embedding_binary = pickle.dumps(embedding)
26
+ instance.embedding = embedding_binary
27
+ instance.save(update_fields=['embedding'])
28
+ return True
29
+ except Exception as e:
30
+ print(f"Error saving embedding: {e}")
31
+ return False
32
+
33
+
34
+ def load_embedding(instance: models.Model) -> Optional[np.ndarray]:
35
+ """
36
+ Load embedding from model instance.
37
+
38
+ Args:
39
+ instance: Django model instance with embedding field.
40
+
41
+ Returns:
42
+ Numpy array of embedding or None if not available.
43
+ """
44
+ if not hasattr(instance, 'embedding') or instance.embedding is None:
45
+ return None
46
+
47
+ try:
48
+ embedding = pickle.loads(instance.embedding)
49
+ return embedding
50
+ except Exception as e:
51
+ print(f"Error loading embedding: {e}")
52
+ return None
53
+
54
+
55
+ def has_embedding(instance: models.Model) -> bool:
56
+ """
57
+ Check if instance has an embedding.
58
+
59
+ Args:
60
+ instance: Django model instance.
61
+
62
+ Returns:
63
+ True if embedding exists, False otherwise.
64
+ """
65
+ return hasattr(instance, 'embedding') and instance.embedding is not None
66
+