dinhquangson commited on
Commit
fb68502
·
verified ·
1 Parent(s): 6079bb1

Upload folder using huggingface_hub

Browse files
.github/workflows/update_space.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Python script
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+
12
+ steps:
13
+ - name: Checkout
14
+ uses: actions/checkout@v2
15
+
16
+ - name: Set up Python
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: '3.9'
20
+
21
+ - name: Install Gradio
22
+ run: python -m pip install gradio
23
+
24
+ - name: Log in to Hugging Face
25
+ run: python -c 'import huggingface_hub; huggingface_hub.login(token="${{ secrets.hf_token }}")'
26
+
27
+ - name: Deploy to Spaces
28
+ run: gradio deploy
.gitignore ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
.gradio/certificate.pem ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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oji: 🐠
4
- colorFrom: green
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 5.30.0
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: chat2excel
3
+ app_file: sql_generator.py
 
 
4
  sdk: gradio
5
+ sdk_version: 5.29.1
 
 
6
  ---
 
 
enable_port_for_ollama.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Cho phép incoming connections đến Ollama
2
+ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /Applications/Ollama.app/Contents/MacOS/ollama
3
+ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblockapp /Applications/Ollama.app/Contents/MacOS/ollama
neo4j.sh ADDED
@@ -0,0 +1 @@
 
 
1
+ docker run --restart always --publish=7474:7474 --publish=7687:7687 neo4j:2025.04.0
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ neo4j
3
+ duckdb
4
+ matplotlib
5
+ openpyxl
6
+ openai
7
+ python-dotenv
sql_generator.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import pandas as pd
4
+ import numpy as np
5
+ from neo4j import GraphDatabase
6
+ from openai import OpenAI
7
+ from dotenv import load_dotenv
8
+ import re
9
+ import duckdb # Thêm thư viện duckdb
10
+ import matplotlib.pyplot as plt
11
+
12
+ # Tải các biến môi trường
13
+ load_dotenv()
14
+
15
+ # Cấu hình OpenAI client với Ollama
16
+ client = OpenAI(
17
+ api_key="ollama", # Ollama không yêu cầu API key thực sự
18
+ base_url=os.getenv("OLLAMA_API_URL", "http://localhost:11434/v1")
19
+ )
20
+
21
+ # Cấu hình Neo4j
22
+ NEO4J_URI = os.getenv("NEO4J_URI", "bolt://localhost:7687")
23
+ NEO4J_USER = os.getenv("NEO4J_USER", "neo4j")
24
+ NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD", "abcd@1234")
25
+
26
+ # Biến toàn cục để lưu trữ schema builder và dataframes
27
+ current_schema_builder = None
28
+ current_dataframes = None # Thêm biến lưu trữ dataframes từ Excel
29
+
30
+ class Neo4jSchemaBuilder:
31
+ def __init__(self, uri, user, password):
32
+ self.driver = GraphDatabase.driver(uri, auth=(user, password))
33
+
34
+ def close(self):
35
+ self.driver.close()
36
+
37
+ def clear_database(self):
38
+ with self.driver.session() as session:
39
+ session.run("MATCH (n) DETACH DELETE n")
40
+
41
+ def create_table_node(self, table_name, columns):
42
+ with self.driver.session() as session:
43
+ session.run("""
44
+ CREATE (t:Table {name: $table_name})
45
+ """, table_name=table_name)
46
+
47
+ for col in columns:
48
+ col_name = col['name']
49
+ col_type = col['type']
50
+ col_desc = col.get('description', '')
51
+
52
+ # Tạo node cho cột
53
+ session.run("""
54
+ MATCH (t:Table {name: $table_name})
55
+ CREATE (c:Column {name: $col_name, type: $col_type, description: $col_desc})
56
+ CREATE (t)-[:HAS_COLUMN]->(c)
57
+ """, table_name=table_name, col_name=col_name, col_type=col_type, col_desc=col_desc)
58
+
59
+ # Nếu là khóa chính
60
+ if col.get('is_primary_key', False):
61
+ session.run("""
62
+ MATCH (c:Column {name: $col_name})
63
+ SET c.is_primary_key = true
64
+ """, col_name=col_name)
65
+
66
+ def create_foreign_key_relationship(self, from_table, from_column, to_table, to_column, relationship_name=None):
67
+ with self.driver.session() as session:
68
+ rel_name = relationship_name or f"REFERENCES"
69
+
70
+ # Tạo quan hệ giữa hai cột
71
+ session.run("""
72
+ MATCH (c1:Column {name: $from_column})<-[:HAS_COLUMN]-(t1:Table {name: $from_table})
73
+ MATCH (c2:Column {name: $to_column})<-[:HAS_COLUMN]-(t2:Table {name: $to_table})
74
+ CREATE (c1)-[:REFERENCES {name: $rel_name}]->(c2)
75
+ """, from_table=from_table, from_column=from_column,
76
+ to_table=to_table, to_column=to_column, rel_name=rel_name)
77
+
78
+ def get_schema_info(self):
79
+ with self.driver.session() as session:
80
+ # Lấy thông tin về các bảng và cột
81
+ tables_result = session.run("""
82
+ MATCH (t:Table)
83
+ OPTIONAL MATCH (t)-[:HAS_COLUMN]->(c)
84
+ RETURN t.name as table_name, collect({name: c.name, type: c.type, description: c.description, is_primary_key: c.is_primary_key}) as columns
85
+ """)
86
+
87
+ tables = {}
88
+ for record in tables_result:
89
+ table_name = record["table_name"]
90
+ columns = record["columns"]
91
+ tables[table_name] = columns
92
+
93
+ # Lấy thông tin về các khóa ngoại
94
+ relationships_result = session.run("""
95
+ MATCH (c1:Column)-[r:REFERENCES]->(c2:Column)
96
+ MATCH (t1:Table)-[:HAS_COLUMN]->(c1)
97
+ MATCH (t2:Table)-[:HAS_COLUMN]->(c2)
98
+ RETURN t1.name as from_table, c1.name as from_column, t2.name as to_table, c2.name as to_column, r.name as relationship_name
99
+ """)
100
+
101
+ relationships = []
102
+ for record in relationships_result:
103
+ relationships.append({
104
+ "from_table": record["from_table"],
105
+ "from_column": record["from_column"],
106
+ "to_table": record["to_table"],
107
+ "to_column": record["to_column"],
108
+ "relationship_name": record["relationship_name"]
109
+ })
110
+
111
+ return {"tables": tables, "relationships": relationships}
112
+
113
+ def find_related_tables(self, keywords):
114
+ with self.driver.session() as session:
115
+ # Tìm các bảng liên quan đến từ khóa
116
+ query = """
117
+ MATCH (t:Table)
118
+ WHERE any(keyword IN $keywords WHERE toLower(t.name) CONTAINS toLower(keyword))
119
+ RETURN t.name as table_name
120
+ UNION
121
+ MATCH (t:Table)-[:HAS_COLUMN]->(c:Column)
122
+ WHERE any(keyword IN $keywords WHERE toLower(c.name) CONTAINS toLower(keyword) OR toLower(c.description) CONTAINS toLower(keyword))
123
+ RETURN t.name as table_name
124
+ """
125
+ result = session.run(query, keywords=keywords)
126
+
127
+ tables = [record["table_name"] for record in result]
128
+
129
+ # Nếu không tìm thấy bảng nào, trả về tất cả các bảng
130
+ if not tables:
131
+ all_tables_query = "MATCH (t:Table) RETURN t.name as table_name"
132
+ all_tables_result = session.run(all_tables_query)
133
+ tables = [record["table_name"] for record in all_tables_result]
134
+
135
+ return tables
136
+
137
+ def get_path_between_tables(self, table1, table2):
138
+ with self.driver.session() as session:
139
+ query = """
140
+ MATCH path = shortestPath((t1:Table {name: $table1})-[*]-(t2:Table {name: $table2}))
141
+ RETURN path
142
+ """
143
+ result = session.run(query, table1=table1, table2=table2)
144
+
145
+ paths = []
146
+ for record in result:
147
+ path = record["path"]
148
+ paths.append(path)
149
+
150
+ return paths
151
+
152
+ # Hàm xử lý khi tải file Excel lên
153
+ def upload_excel(file):
154
+ global current_schema_builder
155
+
156
+ if file is None:
157
+ return "Vui lòng tải lên file Excel."
158
+
159
+ try:
160
+ # Xử lý file Excel
161
+ schema_builder, message = process_excel_file(file.name)
162
+
163
+ if schema_builder:
164
+ current_schema_builder = schema_builder
165
+
166
+ # Lấy thông tin schema để hiển thị
167
+ schema_info = schema_builder.get_schema_info()
168
+ schema_text = "Schema được tạo từ file Excel:\n\n"
169
+
170
+ # Hiển thị thông tin các bảng
171
+ for table_name, columns in schema_info["tables"].items():
172
+ schema_text += f"Bảng: {table_name}\n"
173
+ for col in columns:
174
+ if col["name"]: # Kiểm tra trường hợp cột null
175
+ pk_text = " (PRIMARY KEY)" if col.get("is_primary_key") else ""
176
+ schema_text += f" - {col['name']} ({col['type']}){pk_text}\n"
177
+ schema_text += "\n"
178
+
179
+ # Hiển thị thông tin các mối quan hệ
180
+ schema_text += "Các mối quan hệ:\n"
181
+ for rel in schema_info["relationships"]:
182
+ schema_text += f" {rel['from_table']}.{rel['from_column']} -> {rel['to_table']}.{rel['to_column']}\n"
183
+
184
+ return message + "\n\n" + schema_text
185
+ else:
186
+ return message
187
+
188
+ except Exception as e:
189
+ return f"Lỗi khi xử lý file: {str(e)}"
190
+
191
+ def extract_keywords(query, openai_client=None):
192
+ # Sử dụng Ollama với model qwen3:4b để trích xuất từ khóa
193
+ if openai_client:
194
+ try:
195
+ response = openai_client.chat.completions.create(
196
+ model="qwen3:4b",
197
+ messages=[
198
+ {"role": "system", "content": "Bạn là một assistant giúp trích xuất các từ khóa quan trọng từ câu hỏi để tìm kiếm trong cơ sở dữ liệu. Hãy trả về danh sách các từ khóa, mỗi từ khóa trên một dòng."},
199
+ {"role": "user", "content": f"Trích xuất các từ khóa quan trọng từ câu hỏi sau: \"{query}\""}
200
+ ]
201
+ )
202
+ keywords_text = response.choices[0].message.content
203
+ keywords = [kw.strip() for kw in keywords_text.split('\n') if kw.strip()]
204
+ return keywords
205
+ except Exception as e:
206
+ print(f"Error using Ollama API: {e}")
207
+
208
+ # Phương pháp đơn giản nếu không có Ollama
209
+ words = re.findall(r'\b\w+\b', query.lower())
210
+ stopwords = ['là', 'và', 'của', 'cho', 'từ', 'đến', 'những', 'các', 'tất', 'cả', 'có', 'không', 'trong']
211
+ keywords = [word for word in words if len(word) > 2 and word not in stopwords]
212
+ return keywords
213
+
214
+
215
+ def generate_sql(query, schema_info, related_tables, openai_client=None, error_history=None): # Thêm error_history
216
+ # Chuẩn bị thông tin schema để đưa vào prompt
217
+ schema_text = "Thông tin về schema:\n"
218
+ for table_name, columns in schema_info["tables"].items():
219
+ if table_name in related_tables:
220
+ schema_text += f"Bảng \"{table_name}\":\n"
221
+ for col in columns:
222
+ if col["name"]: # Kiểm tra trường hợp cột null
223
+ pk_text = " (PRIMARY KEY)" if col.get("is_primary_key") else ""
224
+ desc_text = f" - {col.get('description', '')}" if col.get('description') else ""
225
+ schema_text += f" \"{col['name']}\" ({col['type']}){pk_text}{desc_text}\n"
226
+
227
+ # Thêm thông tin về các mối quan hệ
228
+ schema_text += "\nCác mối quan hệ:\n"
229
+ for rel in schema_info["relationships"]:
230
+ if rel["from_table"] in related_tables or rel["to_table"] in related_tables:
231
+ schema_text += f" {rel['from_table']}.{rel['from_column']} -> {rel['to_table']}.{rel['to_column']}\n"
232
+
233
+ # Thêm thông tin lỗi từ các lần thử trước
234
+ messages = [
235
+ {"role": "system", "content": "Bạn là một assistant giúp sinh câu lệnh SQL từ câu hỏi tiếng Việt. Hãy trả về câu lệnh SQL hoàn chỉnh dựa trên schema đã cung cấp. Tên trường và bảng để trong hai dấu \" không dùng dâu _"},
236
+ {"role": "user", "content": f"Schema của cơ sở dữ liệu:\n{schema_text}\n\nCâu hỏi: {query}\n\nHãy sinh câu lệnh SQL để trả lời câu hỏi trên:"}
237
+ ]
238
+
239
+ if error_history:
240
+ for error in error_history:
241
+ messages.append({"role": "assistant", "content": error['sql']})
242
+ messages.append({"role": "user", "content": f"Lỗi khi thực thi SQL: {error['error']}. Vui lòng sửa lại câu lệnh SQL."})
243
+
244
+ # Sử dụng Ollama để sinh SQL
245
+ if openai_client:
246
+ try:
247
+ response = openai_client.chat.completions.create(
248
+ model="qwen3:4b",
249
+ messages=messages
250
+ )
251
+ sql = response.choices[0].message.content
252
+ # Tách phần SQL khỏi các giải thích (nếu có)
253
+ sql_pattern = r"```sql\n(.*?)\n```"
254
+ sql_match = re.search(sql_pattern, sql, re.DOTALL)
255
+ if sql_match:
256
+ sql = sql_match.group(1)
257
+ return sql
258
+ except Exception as e:
259
+ print(f"Error using Ollama API: {e}")
260
+ return f"-- Không thể kết nối với Ollama API\n-- Chi tiết lỗi: {str(e)}\n"
261
+
262
+ # Trường hợp không có Ollama
263
+ tables_str = ", ".join(related_tables)
264
+ return f"-- Vui lòng cấu hình Ollama API để sinh SQL chính xác\nSELECT * FROM {tables_str} LIMIT 10;"
265
+
266
+ def process_excel_file(file_path):
267
+ global current_dataframes # Lưu dataframes vào biến toàn cục
268
+ try:
269
+ # Đọc file Excel
270
+ xl = pd.ExcelFile(file_path)
271
+
272
+ # Tạo schema builder
273
+ schema_builder = Neo4jSchemaBuilder(NEO4J_URI, NEO4J_USER, NEO4J_PASSWORD)
274
+
275
+ # Xóa dữ liệu cũ
276
+ schema_builder.clear_database()
277
+
278
+ # Thông tin về các bảng và quan hệ
279
+ tables_info = {}
280
+ relationships = []
281
+
282
+ # Lưu các dataframe vào biến toàn cục
283
+ current_dataframes = {}
284
+ for sheet_name in xl.sheet_names:
285
+ df = pd.read_excel(file_path, sheet_name=sheet_name)
286
+ current_dataframes[sheet_name] = df
287
+
288
+ print(df)
289
+
290
+ # Các cột của bảng
291
+ columns = []
292
+ for col in df.columns:
293
+ # Xác định kiểu dữ liệu của cột
294
+ sample_value = df[col].dropna().iloc[0] if not df[col].dropna().empty else None
295
+ if pd.isna(sample_value):
296
+ data_type = "VARCHAR"
297
+ elif isinstance(sample_value, (int, np.integer)):
298
+ data_type = "INTEGER"
299
+ elif isinstance(sample_value, (float, np.floating)):
300
+ data_type = "FLOAT"
301
+ elif isinstance(sample_value, pd.Timestamp):
302
+ data_type = "DATETIME"
303
+ else:
304
+ data_type = "VARCHAR"
305
+
306
+ # Kiểm tra xem có phải là khóa chính không (giả định cột đầu tiên là khóa chính)
307
+ is_primary_key = (col == df.columns[0])
308
+
309
+ columns.append({
310
+ "name": col,
311
+ "type": data_type,
312
+ "is_primary_key": is_primary_key,
313
+ "description": ""
314
+ })
315
+
316
+ tables_info[sheet_name] = columns
317
+
318
+ # Tạo node cho bảng
319
+ schema_builder.create_table_node(sheet_name, columns)
320
+
321
+ # Tìm kiếm các quan hệ có thể có (dựa trên tên cột)
322
+ for col in df.columns:
323
+ # Nếu tên cột có định dạng like "table_id", có thể là khóa ngoại
324
+ if "_id" in col.lower() or "id_" in col.lower():
325
+ referenced_table = col.lower().replace("_id", "").replace("id_", "")
326
+ if referenced_table in xl.sheet_names and referenced_table != sheet_name:
327
+ # Thêm vào danh sách các mối quan hệ cần tạo
328
+ relationships.append({
329
+ "from_table": sheet_name,
330
+ "from_column": col,
331
+ "to_table": referenced_table,
332
+ "to_column": xl.parse(referenced_table).columns[0], # Giả định cột đầu tiên là khóa chính
333
+ "relationship_name": f"REFERS_TO_{referenced_table.upper()}"
334
+ })
335
+
336
+ # Tạo các mối quan hệ
337
+ for rel in relationships:
338
+ schema_builder.create_foreign_key_relationship(
339
+ rel["from_table"], rel["from_column"],
340
+ rel["to_table"], rel["to_column"],
341
+ rel["relationship_name"]
342
+ )
343
+
344
+ message = f"Đã xử lý file Excel thành công. Đã tạo {len(tables_info)} bảng và {len(relationships)} mối quan hệ."
345
+ return schema_builder, message
346
+
347
+ except Exception as e:
348
+ return None, f"Lỗi khi xử lý file Excel: {str(e)}"
349
+ def manual_sql_execution(sql_text):
350
+ global current_dataframes
351
+ if current_dataframes is None:
352
+ return None, "Vui lòng tải lên file Excel trước."
353
+
354
+ # Trích xuất SQL từ code block nếu có
355
+ sql_match = re.search(r"```sql\n(.*?)\n```", sql_text, re.DOTALL)
356
+ if sql_match:
357
+ sql = sql_match.group(1).strip()
358
+ else:
359
+ sql = sql_text.strip()
360
+
361
+ try:
362
+ result_df, error = execute_sql(sql, current_dataframes)
363
+ return result_df, error or ""
364
+ except Exception as e:
365
+ return None, str(e)
366
+
367
+ def execute_sql(sql, dataframes):
368
+ """Thực thi câu lệnh SQL trên các dataframe"""
369
+ if not dataframes:
370
+ return None, "Không có dữ liệu được tải. Vui lòng tải file Excel trước."
371
+
372
+ conn = duckdb.connect()
373
+ try:
374
+ # Đăng ký các dataframe vào duckdb
375
+ for table_name, df in dataframes.items():
376
+ conn.register(table_name, df)
377
+
378
+ # Thực thi truy vấn
379
+ result = conn.execute(sql).fetchdf()
380
+ return result, None
381
+ except Exception as e:
382
+ return None, str(e)
383
+ finally:
384
+ # Unregister từng bảng thay vì dùng unregister_all()
385
+ for table_name in dataframes:
386
+ try:
387
+ conn.unregister(table_name) # <-- Sửa ở đây
388
+ except Exception as e:
389
+ print(f"Lỗi khi unregister {table_name}: {str(e)}")
390
+ conn.close()
391
+
392
+ def generate_chart(result_df, label_column, value_column, chart_type="bar"):
393
+ if result_df is None or result_df.empty:
394
+ return None, "Không có dữ liệu để vẽ biểu đồ"
395
+ if not label_column or not value_column:
396
+ return None, "Vui lòng chọn cột nhãn và cột giá trị"
397
+
398
+ try:
399
+ # Kiểm tra sự tồn tại của cột
400
+ if label_column not in result_df.columns:
401
+ return None, f"Cột nhãn '{label_column}' không tồn tại"
402
+ if value_column not in result_df.columns:
403
+ return None, f"Cột giá trị '{value_column}' không tồn tại"
404
+
405
+ # Kiểm tra giá trị số cho cột giá trị (trừ pie chart)
406
+ if chart_type != "pie" and not np.issubdtype(result_df[value_column].dtype, np.number):
407
+ return None, f"Cột giá trị '{value_column}' phải là số"
408
+
409
+ # Tạo biểu đồ
410
+ plt.figure(figsize=(10, 6))
411
+
412
+ if chart_type == "bar":
413
+ plt.bar(result_df[label_column].astype(str), result_df[value_column])
414
+ plt.title(f"Biểu đồ cột {value_column} theo {label_column}")
415
+ plt.xlabel(label_column)
416
+ plt.ylabel(value_column)
417
+ plt.xticks(rotation=45)
418
+
419
+ elif chart_type == "line":
420
+ plt.plot(result_df[label_column].astype(str), result_df[value_column], marker='o')
421
+ plt.title(f"Biểu đồ đường {value_column} theo {label_column}")
422
+ plt.xlabel(label_column)
423
+ plt.ylabel(value_column)
424
+ plt.xticks(rotation=45)
425
+
426
+ elif chart_type == "pie":
427
+ # Kiểm tra giá trị không âm cho pie chart
428
+ if any(result_df[value_column] < 0):
429
+ return None, "Pie chart yêu cầu tất cả giá trị không âm"
430
+ plt.pie(result_df[value_column], labels=result_df[label_column], autopct='%1.1f%%')
431
+ plt.title(f"Biểu đồ tròn {value_column}")
432
+
433
+ else:
434
+ return None, f"Loại chart '{chart_type}' không được hỗ trợ"
435
+
436
+ plt.tight_layout()
437
+ return plt.gcf(), None
438
+
439
+ except Exception as e:
440
+ return None, f"Lỗi khi tạo biểu đồ: {str(e)}"
441
+ def update_dropdowns(result_df):
442
+ if result_df is None or result_df.empty:
443
+ return gr.Dropdown(choices=[], value=None), gr.Dropdown(choices=[], value=None)
444
+
445
+ label_columns = [col.strip() for col in result_df.columns.tolist()]
446
+ numeric_columns = [col.strip() for col in result_df.select_dtypes(include=[np.number]).columns.tolist()]
447
+
448
+ label_value = label_columns[0] if label_columns else None
449
+ value_value = numeric_columns[0] if numeric_columns else None
450
+
451
+ return (
452
+ gr.Dropdown(choices=label_columns, value=label_value),
453
+ gr.Dropdown(choices=numeric_columns, value=value_value)
454
+ )
455
+
456
+ def generate_sql_from_question(question, max_retries):
457
+ global current_schema_builder, current_dataframes
458
+
459
+ if current_schema_builder is None:
460
+ return "Vui lòng tải lên file Excel trước.", None, None
461
+
462
+ if not question:
463
+ return "Vui lòng nhập câu hỏi.", None, None
464
+
465
+ try:
466
+ keywords = extract_keywords(question, client)
467
+ print(f"keywords: {keywords}")
468
+ related_tables = current_schema_builder.find_related_tables(keywords)
469
+ print(f"related_tables: {related_tables}")
470
+ schema_info = current_schema_builder.get_schema_info()
471
+ print(f"schema_info: {schema_info}")
472
+
473
+ error_history = []
474
+ final_sql = None
475
+ result_df = None
476
+ execution_error = None
477
+
478
+ for attempt in range(int(max_retries)):
479
+ # Sinh SQL với thông tin lỗi từ các lần trước
480
+ sql = generate_sql(question, schema_info, related_tables, client, error_history)
481
+ print(f"sql: {sql}")
482
+ if not sql:
483
+ continue
484
+
485
+ # Thực thi SQL
486
+ df, error = execute_sql(sql, current_dataframes)
487
+ if error is None:
488
+ final_sql = sql
489
+ result_df = df
490
+ break
491
+ else:
492
+ error_history.append({'sql': sql, 'error': error})
493
+ execution_error = error
494
+ else:
495
+ # Nếu vượt quá số lần thử
496
+ error_msg = f"Không thể sinh SQL đúng sau {max_retries} lần thử.\nLỗi cuối cùng: {execution_error}"
497
+ return error_msg, None, execution_error
498
+
499
+ # Định dạng kết quả
500
+ sql_text = f"SQL được sinh (lần {attempt + 1}):\n```sql\n{final_sql}\n```"
501
+ return sql_text, result_df, None
502
+
503
+ except Exception as e:
504
+ return f"Lỗi khi sinh SQL: {str(e)}", None, str(e)
505
+
506
+ # Cập nhật giao diện
507
+ with gr.Blocks(title="Ứng dụng sinh SQL từ Excel") as app:
508
+ gr.Markdown("# Ứng dụng sinh SQL từ Excel sử dụng Neo4j và Graph Schema")
509
+
510
+ with gr.Tab("Tải lên Excel"):
511
+ with gr.Row():
512
+ with gr.Column():
513
+ excel_file = gr.File(label="Tải lên file Excel")
514
+ upload_button = gr.Button("Xử lý file Excel")
515
+
516
+ with gr.Column():
517
+ schema_output = gr.Textbox(label="Kết quả xử lý schema", lines=15)
518
+
519
+ with gr.Tab("Sinh SQL"):
520
+ with gr.Row():
521
+ with gr.Column():
522
+ question_input = gr.Textbox(label="Nhập câu hỏi bằng tiếng Việt", placeholder="Ví dụ: Danh sách khách hàng đã mua sản phẩm X")
523
+ max_retries_slider = gr.Slider(minimum=1, maximum=10, step=1, value=5, label="Số lần thử lại tối đa")
524
+ generate_button = gr.Button("Sinh và Chạy SQL")
525
+ sql_output = gr.Textbox(label="Kết quả SQL", lines=10)
526
+ manual_run_button = gr.Button("Chạy SQL Manual")
527
+ with gr.Column():
528
+ result_output = gr.Dataframe(label="Kết quả truy vấn")
529
+
530
+ error_output = gr.Textbox(label="Thông báo lỗi")
531
+ with gr.Tab("Sinh Chart"):
532
+ with gr.Row():
533
+ label_dropdown = gr.Dropdown(label="Chọn cột nhãn")
534
+ value_dropdown = gr.Dropdown(label="Chọn cột giá trị")
535
+ chart_type_dropdown = gr.Dropdown(
536
+ choices=["bar", "line", "pie"],
537
+ value="bar",
538
+ label="Chọn loại biểu đồ"
539
+ )
540
+ chart_button = gr.Button("Sinh Chart")
541
+ chart_output = gr.Plot(label="Biểu đồ kết quả")
542
+ error_output = gr.Textbox(label="Thông báo lỗi")
543
+
544
+ with gr.Tab("Hướng dẫn"):
545
+ gr.Markdown("""
546
+ ## Hướng dẫn sử dụng
547
+
548
+ ### Bước 1: Tải lên file Excel
549
+ - Tải lên file Excel chứa dữ liệu của bạn
550
+ - Mỗi sheet sẽ được xem như một bảng trong cơ sở dữ liệu
551
+ - Hàng đầu tiên sẽ được sử dụng làm tên cột
552
+ - Cột đầu tiên của mỗi bảng sẽ được giả định là khóa chính
553
+ - Hệ thống sẽ tự động phát hiện các mối quan hệ dựa trên tên cột
554
+
555
+ ### Bước 2: Nhập câu hỏi và sinh SQL
556
+ - Nhập câu hỏi bằng tiếng Việt
557
+ - Hệ thống sẽ trích xuất từ khóa từ câu hỏi
558
+ - Dựa vào từ khóa, hệ thống sẽ tìm các bảng liên quan trong graph schema
559
+ - Sau đó, hệ thống sẽ sinh câu lệnh SQL để trả lời câu hỏi
560
+
561
+ ### Cấu hình
562
+ - Cần cài đặt Neo4j và cấu hình kết nối
563
+ - Cần cài đặt Ollama và cấu hình model qwen3:4b and qwen3:4b:
564
+ ```bash
565
+ ollama pull qwen3:4b
566
+ ollama pull qwen3:4b
567
+ ```
568
+ - Đặt URL API của Ollama trong file .env:
569
+ ```
570
+ OLLAMA_API_URL=http://localhost:11434/v1
571
+ ```
572
+ """)
573
+
574
+ # Kết nối sự kiện
575
+ result_output.change(
576
+ fn=update_dropdowns,
577
+ inputs=result_output,
578
+ outputs=[label_dropdown, value_dropdown]
579
+ )
580
+
581
+ upload_button.click(
582
+ fn=upload_excel,
583
+ inputs=excel_file,
584
+ outputs=schema_output
585
+ )
586
+ generate_button.click(
587
+ fn=generate_sql_from_question,
588
+ inputs=[question_input, max_retries_slider],
589
+ outputs=[sql_output, result_output, error_output]
590
+ )
591
+ # Thêm sự kiện cho nút manual
592
+ manual_run_button.click(
593
+ fn=manual_sql_execution,
594
+ inputs=[sql_output],
595
+ outputs=[result_output, error_output]
596
+ )
597
+ # Thêm kết nối sự kiện cho nút sinh chart
598
+ chart_button.click(
599
+ fn=generate_chart,
600
+ inputs=[result_output, label_dropdown, value_dropdown, chart_type_dropdown],
601
+ outputs=[chart_output, error_output]
602
+ )
603
+ # Khởi chạy ứng dụng
604
+ if __name__ == "__main__":
605
+ app.launch(share=True)