Spaces:
Sleeping
Sleeping
Create ai_mapper.py
Browse files- ai_mapper.py +30 -0
ai_mapper.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ai_mapper.py
|
| 2 |
+
|
| 3 |
+
from sentence_transformers import SentenceTransformer, util
|
| 4 |
+
|
| 5 |
+
# Load model once at module level
|
| 6 |
+
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 7 |
+
|
| 8 |
+
def ai_map_fields(extracted_keys, object_fields):
|
| 9 |
+
try:
|
| 10 |
+
mappings = {}
|
| 11 |
+
confidence_scores = {}
|
| 12 |
+
|
| 13 |
+
field_embeddings = model.encode(object_fields, convert_to_tensor=True)
|
| 14 |
+
|
| 15 |
+
for key in extracted_keys:
|
| 16 |
+
if key.lower() in ["name", "email"]:
|
| 17 |
+
continue
|
| 18 |
+
|
| 19 |
+
key_embedding = model.encode(key, convert_to_tensor=True)
|
| 20 |
+
cosine_scores = util.pytorch_cos_sim(key_embedding, field_embeddings)[0]
|
| 21 |
+
best_score_idx = cosine_scores.argmax().item()
|
| 22 |
+
best_match = object_fields[best_score_idx]
|
| 23 |
+
confidence = cosine_scores[best_score_idx].item()
|
| 24 |
+
|
| 25 |
+
mappings[key] = best_match
|
| 26 |
+
confidence_scores[key] = round(confidence, 2)
|
| 27 |
+
|
| 28 |
+
return mappings, confidence_scores, None
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return None, None, str(e)
|