-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_test.py
234 lines (189 loc) ยท 7.58 KB
/
db_test.py
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
231
232
233
234
import os
import pymysql
from sqlalchemy import create_engine
from sqlalchemy.sql import text # SQLAlchemy์ text ๋ชจ๋ ์ถ๊ฐ
import pandas as pd
from dotenv import load_dotenv
from langchain_community.vectorstores import Chroma # ๋ฒกํฐ ์คํ ์ด๋ก Chroma๋ฅผ ์ฌ์ฉ
from langchain_openai import OpenAIEmbeddings # ์
๋ฐ์ดํธ๋ import
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.schema import Document
from concurrent.futures import ThreadPoolExecutor # ๋ณ๋ ฌ ์ฒ๋ฆฌ๋ฅผ ์ํ ๋ชจ๋
from datetime import datetime # ๋ฐฐ์น ์ฃผ๊ธฐ๋ฅผ ์ํ ๋ชจ๋
import time # ์ถ๊ฐ: ์๊ฐ ๋๊ธฐ๋ฅผ ์ํ ๋ชจ๋
import shutil # ๋๋ ํ ๋ฆฌ ์ญ์ ๋ฅผ ์ํ ๋ชจ๋
# .env ํ์ผ ๋ก๋
load_dotenv()
# MariaDB ์ฐ๊ฒฐ ์ ๋ณด
DB_HOST = os.getenv("DB_HOST", "localhost")
DB_PORT = int(os.getenv("DB_PORT", 3306))
DB_USER = os.getenv("DB_USER", "root")
DB_PASSWORD = os.getenv("DB_PASSWORD", "")
DB_NAME = os.getenv("DB_NAME", "test_db")
# ๊ฒฝ๋ก ์ค์
CSV_DIR = r"C:\lecture\FinalProject\InFlow-AI\db_test\csv_files"
CHROMA_DB_DIR = r"C:\lecture\FinalProject\InFlow-AI\db_test"
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# OpenAI ์ค์
embeddings = OpenAIEmbeddings(
openai_api_key=OPENAI_API_KEY, model="text-embedding-ada-002"
)
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
# ๊ธ๋ก๋ฒ ๋ณ์๋ก ์ ์ธ
vectorstore = None
# CSV ๋๋ ํ ๋ฆฌ์ Chroma DB ๋๋ ํ ๋ฆฌ๋ฅผ ์ด๊ธฐํ ๋ฐ ์์ฑ
def initialize_directories():
# Chroma DB ๋๋ ํ ๋ฆฌ ์ด๊ธฐํ
if os.path.exists(CHROMA_DB_DIR):
shutil.rmtree(CHROMA_DB_DIR) # ๊ธฐ์กด Chroma DB ๋๋ ํ ๋ฆฌ ์ญ์
print(f"Cleared Chroma DB directory: {CHROMA_DB_DIR}")
os.makedirs(CHROMA_DB_DIR, exist_ok=True) # Chroma DB ๋๋ ํ ๋ฆฌ ์ฌ์์ฑ
print(f"Created Chroma DB directory: {CHROMA_DB_DIR}")
# CSV ๋๋ ํ ๋ฆฌ ์ด๊ธฐํ
if os.path.exists(CSV_DIR):
shutil.rmtree(CSV_DIR) # ๊ธฐ์กด CSV ๋๋ ํ ๋ฆฌ ์ญ์
print(f"Cleared CSV directory: {CSV_DIR}")
os.makedirs(CSV_DIR, exist_ok=True) # CSV ๋๋ ํ ๋ฆฌ ์ฌ์์ฑ
print(f"Created CSV directory: {CSV_DIR}")
# SQLAlchemy ์์ง ์์ฑ(mariadb )
def connect_sqlalchemy():
try:
engine = create_engine(
f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
)
return engine
except Exception as e:
print(f"Error creating SQLAlchemy engine: {e}")
raise
# ๋ชจ๋ ํ
์ด๋ธ์ ๋ณ๋ ฌ๋ก CSV๋ก ์ ์ฅ
def export_tables_to_csv():
# ๋๋ ํ ๋ฆฌ ์ ํจ์ฑ ๊ฒ์ฌ
if not os.path.exists(CSV_DIR):
raise FileNotFoundError(f"CSV directory does not exist: {CSV_DIR}")
engine = connect_sqlalchemy() # SQLAlchemy ์์ง ์ฌ์ฉ
try:
# ๋ชจ๋ ํ
์ด๋ธ ์ด๋ฆ ๊ฐ์ ธ์ค๊ธฐ
with engine.connect() as connection:
# ์์ SQL ์คํ
result = connection.execute(text("SHOW TABLES;"))
tables = [row[0] for row in result]
# ๋ณ๋ ฌ ์ฒ๋ฆฌ๋ก ๊ฐ ํ
์ด๋ธ ๋ฐ์ดํฐ๋ฅผ CSV๋ก ์ ์ฅ
with ThreadPoolExecutor() as executor:
executor.map(
lambda table: export_table_to_csv_parallel(table, engine), tables
)
except Exception as e:
print(f"Error exporting all tables: {e}")
# ํน์ ํ
์ด๋ธ์ ๋ณ๋ ฌ๋ก CSV๋ก ์ ์ฅ
def export_table_to_csv_parallel(table_name, engine):
try:
# ๋๋ ํ ๋ฆฌ ์ ํจ์ฑ ๊ฒ์ฌ
if not os.path.exists(CSV_DIR):
raise FileNotFoundError(f"CSV directory does not exist: {CSV_DIR}")
# employee ํ
์ด๋ธ์ผ ๊ฒฝ์ฐ ๋ฏผ๊ฐ ์ ๋ณด ์ ์ธ
if table_name == "employee":
query = """
SELECT
employee_id,
employee_number,
employee_role,
gender,
name,
birth_date,
email,
phone_number,
profile_img_url,
join_date,
resignation_date,
resignation_status,
department_code,
attendance_status_type_code,
position_code,
role_code,
duty_code
FROM employee
"""
else:
# ๋ค๋ฅธ ํ
์ด๋ธ์ ์ ์ฒด ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ด
query = f"SELECT * FROM {table_name}"
# ๋ฐ์ดํฐ ํ๋ ์์ผ๋ก ๊ฐ์ ธ์ค๊ธฐ
df = pd.read_sql(query, engine)
# CSV ํ์ผ๋ก ์ ์ฅ
csv_path = os.path.join(CSV_DIR, f"{table_name}.csv")
df.to_csv(csv_path, index=False, encoding="utf-8")
print(f"Exported {table_name} to {csv_path}")
except Exception as e:
print(f"Error exporting table {table_name}: {e}")
# CSV ๋ฐ์ดํฐ๋ฅผ ๋ฒกํฐํํ๊ณ Chroma DB์ ์ ์ฅ
def store_csv_in_chroma():
global vectorstore # ๊ธ๋ก๋ฒ ๋ณ์ ์ฌ์ฉ
documents = []
# csv ํ์ผ ๋ณํ
try:
for csv_file in os.listdir(CSV_DIR):
if csv_file.endswith(".csv"):
csv_path = os.path.join(CSV_DIR, csv_file)
df = pd.read_csv(csv_path)
# ๋ฐ์ดํฐ๊ฐ ๋น์ด ์๋ ๊ฒฝ์ฐ ์คํต
if df.empty:
print(f"Skipped empty file: {csv_file}")
continue
# ๋ฐ์ดํฐ ํ๋ ์์ ํ
์คํธ ๋ฐ์ดํฐ๋ฅผ Document๋ก ๋ณํ
for _, row in df.iterrows():
content = " ".join([f"{col}: {val}" for col, val in row.items()])
documents.append(
Document(page_content=content, metadata={"table": csv_file})
)
# ๋ฌธ์ ๋ถํ ๋ฐ ๋ฒกํฐํ
split_docs = text_splitter.split_documents(documents)
if not split_docs:
raise ValueError("No documents to store in Chroma.")
# Chroma DB์ ์ ์ฅ
vectorstore = Chroma.from_documents(
documents=split_docs,
embedding=embeddings, # ์๋ฒ ๋ฉ ํจ์ ์ ๋ฌ
persist_directory=CHROMA_DB_DIR,
)
print("Data stored in Chroma DB.")
except Exception as e:
print(f"Error storing data in Chroma: {e}")
# RAG ํ
์คํธ
def test_rag_query():
global vectorstore # ๊ธ๋ก๋ฒ ๋ณ์ ์ฌ์ฉ
try:
# ์ง๋ฌธ ํ
์คํธ
query = "์ค์งํ ์ฌ์์ ์ ๋ณด๋?"
retriever = vectorstore.as_retriever(search_kwargs={"k": 1}) # ๊ฒ์ ๊ฒฐ๊ณผ ์ ํ
results = retriever.invoke(query)
print("Query:", query)
print("Results:")
for result in results:
print(result.page_content)
print("Document content:", result.page_content) # ๋ฒกํฐํ๋ ๋ฐ์ดํฐ ํ์ธ
print("Metadata:", result.metadata)
except Exception as e:
print(f"Error testing RAG query: {e}")
# ์ฃผ๊ธฐ์ ๋ฐฐ์น ์คํ
def run_batch():
while True:
print(f"Batch started at {datetime.now()}")
# ๋๋ ํ ๋ฆฌ ์ด๊ธฐํ ๋ฐ ์์ฑ
initialize_directories()
# ์ ํจ์ฑ ๊ฒ์ฌ (์ถ๊ฐ)
if not os.path.exists(CSV_DIR):
print("CSV directory is missing. Aborting batch.")
return
# 1. ๋ชจ๋ ํ
์ด๋ธ ๋ฐ์ดํฐ๋ฅผ CSV๋ก ์ ์ฅ
export_tables_to_csv()
# 2. CSV ๋ฐ์ดํฐ๋ฅผ ๋ฒกํฐ DB์ ์ ์ฅ
store_csv_in_chroma()
print(f"Batch completed at {datetime.now()}")
# 3. RAG ์์คํ
ํ
์คํธ
test_rag_query()
# 4. 1์ผ ๋๊ธฐ
print("Waiting for 24 hours...")
time.sleep(24 * 60 * 60) # 1์ผ(24์๊ฐ)
# ํตํฉ ์คํ
if __name__ == "__main__":
# ๋ฐฐ์น ์คํ
run_batch()