Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,13 +1,22 @@
|
|
|
|
|
|
1 |
# import os
|
2 |
# import gradio as gr
|
3 |
# import numpy as np
|
4 |
# from transformers import AutoTokenizer, AutoModel
|
5 |
# import time
|
|
|
|
|
6 |
# # :white_check_mark: Setup environment
|
7 |
# os.makedirs(os.environ.get("HF_HOME", "./hf_cache"), exist_ok=True)
|
8 |
# hf_token = os.environ.get("HF_TOKEN")
|
9 |
# if not hf_token:
|
10 |
# raise EnvironmentError(":x: Environment variable HF_TOKEN is not set.")
|
|
|
|
|
|
|
|
|
|
|
11 |
# # :white_check_mark: Load model and tokenizer
|
12 |
# text_tokenizer = AutoTokenizer.from_pretrained(
|
13 |
# "nomic-ai/nomic-embed-text-v1.5",
|
@@ -20,23 +29,28 @@
|
|
20 |
# trust_remote_code=True,
|
21 |
# token=hf_token,
|
22 |
# cache_dir=os.environ["HF_HOME"]
|
23 |
-
# )
|
|
|
24 |
# # :white_check_mark: Embedding function
|
25 |
# def get_text_embeddings(text):
|
26 |
# """
|
27 |
# Converts input text into a dense embedding using the Nomic embedding model.
|
28 |
# These embeddings are used to query Qdrant for semantically relevant document chunks.
|
29 |
# """
|
30 |
-
# inputs = text_tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
31 |
-
#
|
|
|
32 |
# embeddings = outputs.last_hidden_state.mean(dim=1)
|
33 |
-
#
|
|
|
|
|
34 |
# # :white_check_mark: Gradio interface function
|
35 |
# def embed_text_interface(text):
|
36 |
-
# strt_time=time.time()
|
37 |
# embedding = get_text_embeddings(text)
|
38 |
# print(f"Total time taken by nomic to embed: {time.time()-strt_time}")
|
39 |
-
# return
|
|
|
40 |
# # :white_check_mark: Gradio UI
|
41 |
# interface = gr.Interface(
|
42 |
# fn=embed_text_interface,
|
@@ -45,6 +59,7 @@
|
|
45 |
# title="Text Embedding with Nomic AI",
|
46 |
# description="Enter some text, and get its embedding vector using Nomic's embedding model."
|
47 |
# )
|
|
|
48 |
# # :white_check_mark: Launch the app
|
49 |
# if __name__ == "__main__":
|
50 |
# interface.launch()
|
@@ -81,35 +96,44 @@ text_model = AutoModel.from_pretrained(
|
|
81 |
cache_dir=os.environ["HF_HOME"]
|
82 |
).to(device) # Move model to GPU if available
|
83 |
|
84 |
-
|
85 |
def get_text_embeddings(text):
|
86 |
-
"""
|
87 |
-
|
88 |
-
|
89 |
-
"""
|
90 |
-
inputs = text_tokenizer(text, return_tensors="pt", padding=True, truncation=True).to(device) # Move inputs to same device as model
|
91 |
-
with torch.no_grad(): # Disable gradient calculation for inference
|
92 |
outputs = text_model(**inputs)
|
93 |
embeddings = outputs.last_hidden_state.mean(dim=1)
|
94 |
-
print(embeddings[0].detach().cpu().numpy())
|
95 |
return embeddings[0].detach().cpu().numpy()
|
96 |
|
97 |
-
|
|
|
|
|
|
|
|
|
|
|
98 |
def embed_text_interface(text):
|
99 |
strt_time = time.time()
|
100 |
embedding = get_text_embeddings(text)
|
101 |
print(f"Total time taken by nomic to embed: {time.time()-strt_time}")
|
102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
-
# :white_check_mark: Gradio UI
|
105 |
interface = gr.Interface(
|
106 |
fn=embed_text_interface,
|
107 |
-
inputs=gr.Textbox(label="
|
108 |
-
outputs=gr.
|
109 |
-
title="Text
|
110 |
-
description="
|
|
|
|
|
|
|
|
|
111 |
)
|
112 |
-
|
113 |
-
# :white_check_mark: Launch the app
|
114 |
if __name__ == "__main__":
|
115 |
interface.launch()
|
|
|
1 |
+
|
2 |
+
|
3 |
# import os
|
4 |
# import gradio as gr
|
5 |
# import numpy as np
|
6 |
# from transformers import AutoTokenizer, AutoModel
|
7 |
# import time
|
8 |
+
# import torch
|
9 |
+
|
10 |
# # :white_check_mark: Setup environment
|
11 |
# os.makedirs(os.environ.get("HF_HOME", "./hf_cache"), exist_ok=True)
|
12 |
# hf_token = os.environ.get("HF_TOKEN")
|
13 |
# if not hf_token:
|
14 |
# raise EnvironmentError(":x: Environment variable HF_TOKEN is not set.")
|
15 |
+
|
16 |
+
# # Check for GPU availability
|
17 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
18 |
+
# print(f"Using device: {device}")
|
19 |
+
|
20 |
# # :white_check_mark: Load model and tokenizer
|
21 |
# text_tokenizer = AutoTokenizer.from_pretrained(
|
22 |
# "nomic-ai/nomic-embed-text-v1.5",
|
|
|
29 |
# trust_remote_code=True,
|
30 |
# token=hf_token,
|
31 |
# cache_dir=os.environ["HF_HOME"]
|
32 |
+
# ).to(device) # Move model to GPU if available
|
33 |
+
|
34 |
# # :white_check_mark: Embedding function
|
35 |
# def get_text_embeddings(text):
|
36 |
# """
|
37 |
# Converts input text into a dense embedding using the Nomic embedding model.
|
38 |
# These embeddings are used to query Qdrant for semantically relevant document chunks.
|
39 |
# """
|
40 |
+
# inputs = text_tokenizer(text, return_tensors="pt", padding=True, truncation=True).to(device) # Move inputs to same device as model
|
41 |
+
# with torch.no_grad(): # Disable gradient calculation for inference
|
42 |
+
# outputs = text_model(**inputs)
|
43 |
# embeddings = outputs.last_hidden_state.mean(dim=1)
|
44 |
+
# print(embeddings[0].detach().cpu().numpy())
|
45 |
+
# return embeddings[0].detach().cpu().numpy()
|
46 |
+
|
47 |
# # :white_check_mark: Gradio interface function
|
48 |
# def embed_text_interface(text):
|
49 |
+
# strt_time = time.time()
|
50 |
# embedding = get_text_embeddings(text)
|
51 |
# print(f"Total time taken by nomic to embed: {time.time()-strt_time}")
|
52 |
+
# return embedding
|
53 |
+
|
54 |
# # :white_check_mark: Gradio UI
|
55 |
# interface = gr.Interface(
|
56 |
# fn=embed_text_interface,
|
|
|
59 |
# title="Text Embedding with Nomic AI",
|
60 |
# description="Enter some text, and get its embedding vector using Nomic's embedding model."
|
61 |
# )
|
62 |
+
|
63 |
# # :white_check_mark: Launch the app
|
64 |
# if __name__ == "__main__":
|
65 |
# interface.launch()
|
|
|
96 |
cache_dir=os.environ["HF_HOME"]
|
97 |
).to(device) # Move model to GPU if available
|
98 |
|
99 |
+
|
100 |
def get_text_embeddings(text):
|
101 |
+
"""Returns embedding as NumPy array"""
|
102 |
+
inputs = text_tokenizer(text, return_tensors="pt", padding=True, truncation=True).to(device)
|
103 |
+
with torch.no_grad():
|
|
|
|
|
|
|
104 |
outputs = text_model(**inputs)
|
105 |
embeddings = outputs.last_hidden_state.mean(dim=1)
|
|
|
106 |
return embeddings[0].detach().cpu().numpy()
|
107 |
|
108 |
+
def format_embedding(embedding):
|
109 |
+
"""Formats the embedding as 'embedding: [x.xx, x.xx, ...]'"""
|
110 |
+
formatted = ", ".join([f"{x:.3f}" for x in embedding])
|
111 |
+
return f"embedding: [{formatted}]"
|
112 |
+
import json
|
113 |
+
|
114 |
def embed_text_interface(text):
|
115 |
strt_time = time.time()
|
116 |
embedding = get_text_embeddings(text)
|
117 |
print(f"Total time taken by nomic to embed: {time.time()-strt_time}")
|
118 |
+
|
119 |
+
# Convert to list and format for display
|
120 |
+
embedding_list = embedding.tolist()
|
121 |
+
formatted = {
|
122 |
+
"embedding": embedding_list,
|
123 |
+
"shape": len(embedding_list)
|
124 |
+
}
|
125 |
+
return formatted
|
126 |
|
|
|
127 |
interface = gr.Interface(
|
128 |
fn=embed_text_interface,
|
129 |
+
inputs=gr.Textbox(label="Input Text", lines=5),
|
130 |
+
outputs=gr.JSON(label="Embedding Vector"), # Using JSON output
|
131 |
+
title="Nomic Text Embeddings",
|
132 |
+
description="Returns embeddings as a Python list",
|
133 |
+
examples=[
|
134 |
+
["This is a sample text"],
|
135 |
+
["Another example sentence"]
|
136 |
+
]
|
137 |
)
|
|
|
|
|
138 |
if __name__ == "__main__":
|
139 |
interface.launch()
|