Spaces:
Running
on
Zero
Running
on
Zero
File size: 7,920 Bytes
d6a2797 a74f794 90a420e a74f794 d6a2797 a1e6264 d6a2797 1c6b863 d6a2797 41e5bd2 a1e6264 480c871 41e5bd2 d6a2797 a1e6264 36c2b65 a1e6264 36c2b65 636ff10 a1e6264 20c5a04 70b71a3 20c5a04 a1e6264 6c506a1 5a16c22 70b71a3 5a16c22 6c506a1 5a16c22 6c506a1 5a16c22 0122be6 bd4cb9f 5a16c22 d6a2797 70b71a3 d6a2797 a1e6264 a74f794 36c2b65 41e5bd2 36c2b65 93f3952 d6a2797 93f3952 d6a2797 93f3952 d6a2797 41e5bd2 d6a2797 a74f794 d6a2797 a74f794 d6a2797 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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 |
import psycopg2
from sentence_transformers import SentenceTransformer
from fastapi import APIRouter, HTTPException
import os
class ProductDatabase:
def __init__(self, database_url):
self.database_url = database_url
self.conn = None
self.model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
def connect(self):
self.conn = psycopg2.connect(self.database_url)
def close(self):
if self.conn:
self.conn.close()
def setup_vector_extension_and_column(self):
with self.conn.cursor() as cursor:
# pgvector拡張機能のインストール
cursor.execute("CREATE EXTENSION IF NOT EXISTS vector;")
# ベクトルカラムの追加
cursor.execute("ALTER TABLE products ADD COLUMN IF NOT EXISTS vector_col vector(384);")
self.conn.commit()
def get_embedding(self, text):
embedding = self.model.encode(text)
return embedding
def insert_vector(self, product_id, text):
vector = self.get_embedding(text).tolist() # ndarray をリストに変換
with self.conn.cursor() as cursor:
cursor.execute("UPDATE diamondprice SET vector_col = %s WHERE id = %s", (vector, product_id))
self.conn.commit()
def search_similar_vectors(self, query_text, top_k=10):
query_vector = self.get_embedding(query_text).tolist() # ndarray をリストに変換
with self.conn.cursor() as cursor:
cursor.execute("""
SELECT id,price,carat, cut, color, clarity, depth, diamondprice.table, x, y, z, vector_col <=> %s::vector AS distance
FROM diamondprice
WHERE vector_col IS NOT NULL
ORDER BY distance asc
LIMIT %s;
""", (query_vector, top_k))
results = cursor.fetchall()
return results
def search_similar_all(self, query_text, top_k=5):
query_vector = self.get_embedding(query_text).tolist() # ndarray をリストに変換
with self.conn.cursor() as cursor:
cursor.execute("""
SELECT id,carat, cut, color, clarity, depth, diamondprice.table, x, y, z
FROM diamondprice
order by id asc
limit 10000000
""", (query_vector, top_k))
results = cursor.fetchall()
return results
def create_index():
# データベース接続情報
DATABASE_URL = os.getenv("postgre_url")
# ProductDatabaseクラスのインスタンスを作成
db = ProductDatabase(DATABASE_URL)
# データベースに接続
db.connect()
try:
# pgvector拡張機能のインストールとカラムの追加
db.setup_vector_extension_and_column()
print("Vector extension installed and column added successfully.")
query_text="1"
results = db.search_similar_all(query_text)
print("Search results:")
DEBUG=1
if DEBUG==1:
for result in results:
print(result)
id = result[0]
sample_text = str(result[1])+str(result[2])+str(result[3])+str(result[4])+str(result[5])+str(result[6])+str(result[7])+str(result[8])+str(result[9])
print(sample_text)
db.insert_vector(id, sample_text)
#return
# サンプルデータの挿入
#sample_text = """"""
#sample_product_id = 1 # 実際の製品IDを使用
#db.insert_vector(sample_product_id, sample_text)
#db.insert_vector(2, sample_text)
#print(f"Vector inserted for product ID {sample_product_id}.")
# ベクトル検索
query_text = "2.03Very GoodJSI262.058.08.068.125.05"
query_text = "2.03Very GoodJSI2"
#query
#query_text = "2.03-Very Good-J-SI2-62.2-58.0-7.27-7.33-4.55"
results = db.search_similar_vectors(query)#query_text)
res_all = ""
print("Search results:")
for result in results:
print(result)
res_all += str(result)+"\r\n"
return res_all
finally:
# 接続を閉じる
db.close()
def calculate(query):
# データベース接続情報
DATABASE_URL = os.getenv("postgre_url")
# ProductDatabaseクラスのインスタンスを作成
db = ProductDatabase(DATABASE_URL)
# データベースに接続
db.connect()
try:
# pgvector拡張機能のインストールとカラムの追加
db.setup_vector_extension_and_column()
print("Vector extension installed and column added successfully.")
query_text="1"
results = db.search_similar_all(query_text)
print("Search results:")
DEBUG=0
if DEBUG==1:
for result in results:
print(result)
id = result[0]
sample_text = str(result[1])+str(result[2])+str(result[3])+str(result[4])+str(result[5])+str(result[6])+str(result[7])+str(result[8])+str(result[9])
print(sample_text)
db.insert_vector(id, sample_text)
#return
# サンプルデータの挿入
#sample_text = """"""
#sample_product_id = 1 # 実際の製品IDを使用
#db.insert_vector(sample_product_id, sample_text)
#db.insert_vector(2, sample_text)
#print(f"Vector inserted for product ID {sample_product_id}.")
# ベクトル検索
query_text = "2.03Very GoodJSI262.058.08.068.125.05"
query_text = "2.03Very GoodJSI2"
#query
#query_text = "2.03-Very Good-J-SI2-62.2-58.0-7.27-7.33-4.55"
results = db.search_similar_vectors(query)#query_text)
res_all = ""
print("Search results:")
for result in results:
print(result)
res_all += str(result)+"\r\n"
return res_all
finally:
# 接続を閉じる
db.close()
def main():
# データベース接続情報
DATABASE_URL = os.getenv("postgre_url")
# ProductDatabaseクラスのインスタンスを作成
db = ProductDatabase(DATABASE_URL)
# データベースに接続
db.connect()
try:
# pgvector拡張機能のインストールとカラムの追加
db.setup_vector_extension_and_column()
print("Vector extension installed and column added successfully.")
query_text="1"
results = db.search_similar_all(query_text)
print("Search results:")
DEBUG=0
if DEBUG==1:
for result in results:
print(result)
id = result[0]
sample_text = str(result[1])+str(result[2])+str(result[3])+str(result[4])+str(result[5])+str(result[6])+str(result[7])+str(result[8])+str(result[9])
print(sample_text)
db.insert_vector(id, sample_text)
#return
# サンプルデータの挿入
#sample_text = """"""
#sample_product_id = 1 # 実際の製品IDを使用
#db.insert_vector(sample_product_id, sample_text)
#db.insert_vector(2, sample_text)
#print(f"Vector inserted for product ID {sample_product_id}.")
# ベクトル検索
query_text = "2.03Very GoodJSI262.058.08.068.125.05"
query_text = "2.03Very GoodJSI2"
#query_text = "2.03-Very Good-J-SI2-62.2-58.0-7.27-7.33-4.55"
results = db.search_similar_vectors(query_text)
res_all = ""
print("Search results:")
for result in results:
print(result)
res_all += result+""
finally:
# 接続を閉じる
db.close()
if __name__ == "__main__":
main()
|