-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext2sql.py
More file actions
1884 lines (1571 loc) · 80.1 KB
/
text2sql.py
File metadata and controls
1884 lines (1571 loc) · 80.1 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from llama_index.core.program import LLMTextCompletionProgram
import pandas as pd
from typing import List, Tuple, Optional, Dict, Any, Set
from decimal import Decimal
from datetime import datetime, date
from sqlalchemy import text
import json
import os
import uuid
import psycopg2
from private_gpt.settings.settings import Settings
from private_gpt.components.llm.llm_component import LLMComponent
from private_gpt.core_logger import logger
from private_gpt.components.embedding.embedding_component import EmbeddingComponent
from sqlalchemy import (
create_engine,
MetaData
)
import re
import time
from llama_index.core.objects import (
SQLTableNodeMapping,
ObjectIndex,
SQLTableSchema,
)
from llama_index.core import SQLDatabase
from llama_index.core.retrievers import SQLRetriever
from typing import List
from llama_index.core.query_pipeline import FnComponent
from llama_index.core import PromptTemplate
from llama_index.core.bridge.pydantic import Field
from llama_index.core.llms import ChatMessage, MessageRole
from llama_index.core.query_pipeline import CustomQueryComponent
# from llama_index.core.prompts.default_prompts import DEFAULT_TEXT_TO_SQL_PROMPT
from llama_index.core.query_pipeline import FnComponent
from llama_index.core.llms import ChatResponse
from llama_index.core.query_pipeline import (
QueryPipeline as QP,
InputComponent,
)
from injector import inject
from llama_index.vector_stores.qdrant import QdrantVectorStore
import qdrant_client.models
from .query_sanitize import QuerySanitizer, TableInfo
import qdrant_client
from .qdrant_cache import QdrantQueryCache
from llama_index.core.prompts.prompt_type import PromptType
from private_gpt.server.chat.redis_history import RedisHistoryHandler
from private_gpt.server.google_calendar.load_config import load_config
from private_gpt.server.google_calendar.user_functions import *
config = load_config()
POSTGRES_PASSWORD = os.getenv('POSTGRES_PASSWORD')
POSTGRES_HOST = os.getenv('POSTGRES_HOST', 'localhost')
POSTGRES_PORT = '5432'
POSTGRES_DB = 'postgres'
QDRANT_URL = os.getenv("QDRANT_URL")
QDRANT_API_KEY = os.getenv("QDRANT_API_KEY")
REDIS_TTL = config["redis_timeout"]
FORBIDDEN_NAMES = {
# SQL Reserved Keywords
'abort', 'absolute', 'access', 'action', 'add', 'admin', 'after', 'aggregate', 'alias',
'all', 'allocate', 'alter', 'analyse', 'analyze', 'and', 'any', 'array', 'as', 'asc',
'assertion', 'assignment', 'asymmetric', 'at', 'authorization', 'backward', 'before',
'begin', 'between', 'bigint', 'binary', 'bit', 'boolean', 'both', 'by', 'cache',
'call', 'cascade', 'cascaded', 'case', 'cast', 'catalog', 'char', 'character',
'characteristics', 'check', 'checkpoint', 'class', 'close', 'cluster', 'coalesce',
'collate', 'column', 'commit', 'committed', 'concurrently', 'condition', 'connect',
'connection', 'constraint', 'constraints', 'continue', 'convert', 'copy', 'cost',
'create', 'cross', 'csv', 'current', 'current_catalog', 'current_date', 'current_role',
'current_schema', 'current_time', 'current_timestamp', 'current_user', 'cursor',
'cycle', 'data', 'database', 'day', 'deallocate', 'dec', 'decimal', 'declare',
'default', 'defaults', 'deferrable', 'deferred', 'definer', 'delete', 'delimiter',
'delimiters', 'desc', 'dictionary', 'disconnect', 'distinct', 'do', 'domain', 'double',
'drop', 'each', 'else', 'end', 'escape', 'except', 'exclude', 'exclusive', 'execute',
'exists', 'explain', 'external', 'extract', 'false', 'fetch', 'filter', 'first',
'float', 'following', 'for', 'force', 'foreign', 'forward', 'freeze', 'from', 'full',
'function', 'functions', 'global', 'grant', 'granted', 'greatest', 'group', 'handler',
'having', 'header', 'hold', 'hour', 'identity', 'if', 'ilike', 'immediate', 'immutable',
'implicit', 'in', 'including', 'increment', 'index', 'indexes', 'inherit', 'inherits',
'initially', 'inner', 'input', 'insensitive', 'insert', 'instead', 'int', 'integer',
'intersect', 'interval', 'into', 'invoker', 'is', 'isnull', 'isolation', 'join', 'key',
'language', 'large', 'last', 'leading', 'least', 'left', 'level', 'like', 'limit',
'listen', 'load', 'local', 'localtime', 'localtimestamp', 'location', 'lock', 'login',
'logout', 'mapping', 'match', 'maxvalue', 'minute', 'minvalue', 'mode', 'month',
'move', 'names', 'national', 'natural', 'nchar', 'new', 'next', 'no', 'none', 'not',
'nothing', 'notify', 'null', 'nullif', 'numeric', 'object', 'of', 'off', 'offset',
'oids', 'old', 'on', 'only', 'operator', 'option', 'or', 'order', 'ordinality',
'outer', 'over', 'overlaps', 'overlay', 'owned', 'owner', 'parser', 'partial',
'partition', 'passing', 'password', 'path', 'pg_attribute', 'pg_class', 'pg_type',
'pg_tables', 'pg_views', 'pg_indexes', 'pg_user', 'pg_roles', 'pg_proc', 'pg_stat',
'pg_database', 'pg_namespace', 'placing', 'plans', 'policy', 'position', 'preceding',
'precision', 'prepare', 'primary', 'prior', 'privileges', 'procedure', 'procedures',
'program', 'quote', 'range', 'read', 'real', 'reassign', 'recheck', 'record',
'recursive', 'ref', 'references', 'referencing', 'refresh', 'reindex', 'relative',
'release', 'rename', 'repeatable', 'replace', 'replica', 'reset', 'restart',
'restrict', 'return', 'returns', 'revoke', 'right', 'role', 'rollback', 'row', 'rows',
'rule', 'savepoint', 'schema', 'scroll', 'search', 'second', 'security', 'select',
'sequence', 'sequences', 'serial', 'server', 'session', 'set', 'sets', 'share',
'show', 'similar', 'simple', 'smallint', 'snapshot', 'some', 'stable', 'standalone',
'start', 'statement', 'statistics', 'stdin', 'stdout', 'storage', 'strict', 'strip',
'subquery', 'substring', 'symmetric', 'sysid', 'system', 'table', 'tables', 'tablespace',
'temp', 'template', 'temporary', 'then', 'time', 'timestamp', 'to', 'trailing',
'transaction', 'transform', 'trigger', 'true', 'truncate', 'trusted', 'type', 'types',
'unbounded', 'uncommitted', 'unencrypted', 'union', 'unique', 'unknown', 'unlisten',
'until', 'update', 'user', 'using', 'vacuum', 'valid', 'validate', 'validator', 'value',
'values', 'varchar', 'variadic', 'varying', 'verbose', 'version', 'view', 'volatile',
'when', 'where', 'whitespace', 'window', 'with', 'within', 'without', 'work', 'wrapper',
'write', 'xml', 'xmlagg', 'xmlattributes', 'xmlbinary', 'xmlconcat', 'xmlelement',
'xmlexists', 'xmlforest', 'xmlnamespaces', 'xmlparse', 'xmlpi', 'xmlroot', 'xmlserialize',
'year', 'zone',
# Common Data Types
'serial', 'bigserial', 'int', 'int2', 'int4', 'int8', 'float4', 'float8', 'numeric',
'boolean', 'char', 'text', 'timestamp', 'time', 'date', 'interval', 'uuid'
}
rewrite = (
"Please write a query to a semantic search engine using the current conversation.\n"
"\n"
"\n"
"{chat_history_str}"
"\n"
"\n"
"Latest message: {query_str}\n"
'Query:"""\n'
)
class ChatInputComponent(CustomQueryComponent):
llm: Any = Field(description="Language model to use for query refinement")
system_prompt: Optional[str] = Field(
default="Your task is to analyze the current query in the context of the chat history "
"and refine it to be more precise and complete. Maintain the original intent "
"while incorporating relevant context from previous interactions. Output only "
"the refined query without explanations.",
description="System prompt for query refinement"
)
def _validate_component_inputs(
self, input: Dict[str, Any]
) -> Dict[str, Any]:
logger.info("Validating inputs")
return input
@property
def _input_keys(self) -> Set[str]:
return {"chat_history", "query_str"}
@property
def _output_keys(self) -> Set[str]:
return {"query_str"} # Changed from 'response' to 'query_str'
def _prepare_context(
self,
chat_history: List[ChatMessage],
query_str: str
) -> List[ChatMessage]:
messages = []
# Add system prompt
if self.system_prompt:
messages.append(ChatMessage(role="system", content=self.system_prompt))
# Add chat history
for msg in chat_history:
messages.append(msg)
# Add current query
messages.append(ChatMessage(role="user", content=query_str))
return messages
def _run_component(self, **kwargs) -> Dict[str, Any]:
chat_history = kwargs.get("chat_history", [])
query_str = kwargs.get("query_str", "")
try:
# Prepare context with chat history and current query
context = self._prepare_context(
chat_history=chat_history,
query_str=query_str
)
if chat_history:
# Get refined query from LLM
refined_query = self.llm.chat(messages=context)
else:
refined_query = query_str
# Return the refined query
return {"query_str": refined_query}
except Exception as e:
logger.error(f"Error in query refinement: {str(e)}")
# If there's an error, return original query
return {"query_str": query_str}
# async def _arun_component(self, **kwargs: Any) -> Dict[str, Any]:
# logger.info("arun")
# chat_history = kwargs["chat_history"]
# query_str = kwargs["query_str"]
# logger.info(query_str)
# logger.info(chat_history)
# prepared_context = self._prepare_context(chat_history, query_str)
# response = await self.llm.achat(prepared_context)
# logger.info(response)
# return {"response": response}
class InitializeClients:
conn_str = None
query_cache = None
engine = None
conn = None
cur = None
metadata_obj = None
filtered_table_infos = None
sql_database = None
obj_retriever = None
sql_retriever = None
collection_name = "text2sql_query_cache"
@classmethod
def initialize(cls):
# print("initialize")
cls.conn_str = f'postgresql://postgres:{POSTGRES_PASSWORD}@{POSTGRES_HOST}/{POSTGRES_DB}'
# Add error handling for Qdrant initialization
if QDRANT_URL:
try:
cls.client = qdrant_client.QdrantClient(
url=QDRANT_URL,
api_key=QDRANT_API_KEY
)
print(f"Successfully connected to Qdrant at {QDRANT_URL}")
except Exception as e:
print(f"Warning: Failed to initialize Qdrant connection: {str(e)}")
# print("The application will continue without query caching.")
cls.client = None
else:
cls.client = None
return cls
@classmethod
def _create_collection(cls):
"""Explicitly create Qdrant collection"""
try:
collections = cls.client.get_collections()
# print(f"Current collections: {collections}")
cls.client.get_collection(cls.collection_name)
except Exception:
# print(f"creating collection: {cls.collection_name}")
cls.client.create_collection(
collection_name=cls.collection_name,
vectors_config=qdrant_client.models.VectorParams(
size=1024,
distance=qdrant_client.models.Distance.COSINE
)
)
cls.vector_store = QdrantVectorStore(
client=cls.client,
collection_name=cls.collection_name
)
@classmethod
def initialize_settings(cls):
logger.info("Initializing database schemas and user mapping...")
try:
cls.engine = create_engine(cls.conn_str)
# print("create engine")
cls.conn = psycopg2.connect(
host=POSTGRES_HOST,
password=POSTGRES_PASSWORD,
user='postgres',
database=POSTGRES_DB
)
# print("pyscop connect")
cls.conn.autocommit = True
cls.cur = cls.conn.cursor()
# Create necessary schemas
cls.cur.execute("CREATE SCHEMA IF NOT EXISTS csv_data")
cls.cur.execute("CREATE SCHEMA IF NOT EXISTS query_history")
cls.cur.execute("CREATE SCHEMA IF NOT EXISTS auth")
cls.conn.commit()
# Initialize metadata object and reflect schemas
cls.metadata_obj = MetaData()
cls.metadata_obj.reflect(bind=cls.engine, schema='csv_data')
# cls.metadata_obj.reflect(bind=cls.engine, schema='auth')
cls._create_collection()
logger.info("Database initialization completed successfully")
except Exception as e:
logger.error(f"Error during database initialization: {str(e)}")
raise RuntimeError("Failed to initialize database connections") from e
@classmethod
def load_existing_database(cls):
"""
Retrieve existing database from PostgreSQL's csv_data schema and generate
table summaries using LLM.
"""
print("Retrieving existing database from PostgreSQL csv_data schema...")
try:
cls.table_names = []
cls.table_infos = []
# Get list of tables in csv_data schema
tables_query = """
SELECT tablename
FROM pg_catalog.pg_tables
WHERE schemaname = 'csv_data';
"""
cls.cur.execute(tables_query)
tables = cls.cur.fetchall()
if not tables:
logger.info("No existing tables found in csv_data schema")
return
for table_data in tables:
table_name = table_data[0]
fallback_table_info = TableInfo(
table_name=table_name,
table_summary=f"Table containing data from {table_name}"
)
cls.table_infos.append(fallback_table_info)
logger.info(f"Successfully loaded {len(cls.table_infos)} tables from csv_data schema")
except Exception as e:
logger.error(f"Error loading database schema: {str(e)}")
cls.table_infos = []
raise
finally:
if hasattr(cls, 'cur') and cls.cur is not None:
cls.cur.close()
@classmethod
def check_user_mapping(cls, email):
"""
Check if a user email exists in the mapping table and return their UUID.
If the email doesn't exist, create a new mapping.
"""
try:
cls.cur = cls.conn.cursor()
# Check if email exists
cls.cur.execute("""
SELECT id, login_count
FROM auth.email_mapping
WHERE email = %s
""", (email,))
result = cls.cur.fetchone()
if result:
# Update existing user's login information
user_id, login_count = result
cls.cur.execute("""
UPDATE auth.email_mapping
SET last_login_date = NOW(),
has_logged_in = TRUE,
login_count = %s
WHERE id = %s
""", (login_count + 1, user_id))
else:
# Create new user mapping
user_id = uuid.uuid4()
cls.cur.execute("""
INSERT INTO auth.email_mapping
(id, email, first_login_date, last_login_date, has_logged_in, login_count)
VALUES (%s, %s, NOW(), NOW(), TRUE, 1)
""", (str(user_id), email))
cls.conn.commit()
return str(user_id)
except Exception as e:
cls.conn.rollback()
logger.error(f"Error in user mapping operation: {str(e)}")
raise
finally:
if cls.cur is not None:
cls.cur.close()
@classmethod
def get_table_infos(cls):
return cls.table_infos
@classmethod
def get_table_names(cls):
return cls.table_names
@classmethod
def get_engine(cls):
if not cls.engine:
raise RuntimeError("Engine not initialized")
return cls.engine
@classmethod
def get_metadata(cls):
if not cls.metadata_obj:
raise RuntimeError("Metadata not initialized")
return cls.metadata_obj
@classmethod
def get_conn(cls):
if not cls.conn:
raise RuntimeError("Connection not initialized")
return cls.conn
@classmethod
def get_query(cls):
return cls.client
@classmethod
def get_vector_store(cls):
return cls.vector_store
@classmethod
def close(cls):
if cls.conn:
cls.conn.close()
if cls.engine:
cls.engine.dispose()
if cls.client:
cls.client.close()
class Text2SQL:
settings: Settings
@inject
def __init__(self, llmcomponent: LLMComponent, settings: Settings, embeddng: EmbeddingComponent, ):
# self.csv_path = csv_path
self.llm_service = llmcomponent
self.settings = settings
self.llm = self.llm_service.llm
# self.structured_llm = self.llm.as_structured_llm()
self.query_sanitizer = QuerySanitizer(self.llm)
self.sql_query = None
self.embedding = embeddng
self.engine = InitializeClients.get_engine()
self.metadata_obj = InitializeClients.get_metadata()
self.conn = InitializeClients.get_conn()
self.query_client = InitializeClients.get_query()
self.vector_store = InitializeClients.get_vector_store()
self.table_infos = InitializeClients.get_table_infos()
self.table_names = InitializeClients.get_table_names()
self.query_cache = QdrantQueryCache(self.embedding.embedding_model, self.vector_store)
prompt_str = """\
Give me a summary of the table with the following JSON format.
- The original table name is provided and must remain unchanged.
- Do NOT output a generic table name (e.g. table, my_table).
Original Table Name: {table_name}
Table:
{table_str}
Summary: """
self.program = LLMTextCompletionProgram.from_defaults(
output_cls=TableInfo,
llm=self.llm,
prompt_template_str=prompt_str,
)
def sanitize_column_name(self, col_name: str) -> str:
"""
Sanitize column names for PostgreSQL compatibility.
Args:
col_name (str): Original column name
Returns:
str: Sanitized column name that is PostgreSQL compatible
Features:
- Converts to lowercase
- Replaces spaces and special characters with underscores
- Ensures name starts with a letter
- Truncates to PostgreSQL's length limit
- Handles duplicate underscores
- Ensures unique names by adding numeric suffix if needed
- Avoids forbidden names by appending a harmless suffix
"""
if not isinstance(col_name, str):
col_name = str(col_name)
# Convert to lowercase
clean_name = col_name.lower().strip()
# Replace spaces and special characters with underscores
clean_name = re.sub(r'[^a-z0-9_]', '_', clean_name)
# Replace multiple underscores with single underscore
clean_name = re.sub(r'_+', '_', clean_name)
# Remove leading and trailing underscores
clean_name = clean_name.strip('_')
# Ensure name starts with a letter
if not clean_name[0].isalpha():
clean_name = 'tmp_' + clean_name
# PostgreSQL has a 63-byte limit for identifiers
if len(clean_name) > 63:
# If truncating would create a name ending with underscore, remove it
clean_name = clean_name[:63].rstrip('_')
# Ensure we have at least one character
if not clean_name:
clean_name = 'column'
# Check if the sanitized name is a forbidden PostgreSQL keyword
if clean_name in FORBIDDEN_NAMES:
clean_name = clean_name + '_col' # Append a harmless suffix
return clean_name
def process_data(self, file_paths: list[str], uuid: str) -> list[pd.DataFrame]:
"""Load CSV, Excel, and PDF data into PostgreSQL's csv_data schema using optimized table creation.
Args:
file_paths: List of paths to CSV, Excel, or PDF files to process
uuid: User UUID to prefix table names
Returns:
list[pd.DataFrame]: List of processed dataframes
"""
dfs = []
self.metadata_obj = MetaData()
self.table_names = []
self.ingestion_timestamps = []
for file_path in file_paths:
file_name = os.path.basename(file_path)
logger.info(f"Processing file: {file_path}")
try:
if file_path.endswith(".csv"):
df = pd.read_csv(file_path)
df.columns = [self.sanitize_column_name(col) for col in df.columns]
# Create table name with full UUID prefix
base_table_name = self.sanitize_column_name(os.path.splitext(file_name)[0])
table_name = f"{uuid}_{base_table_name}"
# If base name is too long, truncate it while keeping full UUID
if len(table_name) > 63:
max_base_length = 63 - len(uuid) - 1 # -1 for underscore
base_table_name = base_table_name[:max_base_length]
table_name = f"{uuid}_{base_table_name}"
self.table_names.append(table_name)
ingestion_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.ingestion_timestamps.append(ingestion_timestamp)
self.create_table_from_dataframe_(
df=df,
table_name=table_name,
)
logger.info(f"Created table csv_data.{table_name}")
dfs.append(df)
elif file_path.endswith((".xlsx", ".xls")):
excel_file = pd.ExcelFile(file_path)
sheet_names = excel_file.sheet_names
for sheet_name in sheet_names:
logger.info(f"Processing sheet: {sheet_name}")
df = pd.read_excel(file_path, sheet_name=sheet_name)
if df.empty:
logger.info(f"Skipping empty sheet: {sheet_name}")
continue
df.columns = [self.sanitize_column_name(col) for col in df.columns]
base_name = self.sanitize_column_name(os.path.splitext(file_name)[0])
sheet_name_clean = self.sanitize_column_name(sheet_name)
# Create table name with full UUID prefix
table_name = f"{uuid}_{base_name}_{sheet_name_clean}"
# If combined name is too long, truncate the base name and sheet name while keeping full UUID
if len(table_name) > 63:
remaining_space = 63 - len(uuid) - 2 # -2 for two underscores
# Split remaining space between base name and sheet name
max_part_length = remaining_space // 2
base_name = base_name[:max_part_length]
sheet_name_clean = sheet_name_clean[:max_part_length]
table_name = f"{uuid}_{base_name}_{sheet_name_clean}"
self.table_names.append(table_name)
ingestion_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.ingestion_timestamps.append(ingestion_timestamp)
self.create_table_from_dataframe_(
df=df,
table_name=table_name
)
logger.info(f"Created table csv_data.{table_name}")
dfs.append(df)
# elif file_path.endswith(".pdf"):
# # Process PDF using Camelot
# logger.info(f"Attempting to extract tables from PDF: {file_name}")
# tables_lattice = camelot.read_pdf(
# file_path,
# pages='all',
# flavor='lattice'
# )
# tables_stream = camelot.read_pdf(
# file_path,
# pages='all',
# flavor='stream'
# )
# tables = tables_lattice + tables_stream
# if tables:
# for i, table in enumerate(tables):
# df = table.df
# df.columns = [self.sanitize_column_name(col) for col in df.iloc[0]] # Use first row as header
# df = df[1:] # Remove the first row which is now headers
# base_name = self.sanitize_column_name(os.path.splitext(file_name)[0])
# table_name = f"{base_name}_table_{i}"
# if len(table_name) > 63:
# table_name = table_name[:63]
# self.table_names.append(table_name)
# ingestion_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# self.ingestion_timestamps.append(ingestion_timestamp)
# self.create_table_from_dataframe_(
# df=df,
# table_name=table_name
# )
# logger.info(f"Created table csv_data.{table_name}")
# dfs.append(df)
# else:
# logger.info(f"No tables found in PDF: {file_name}")
else:
logger.info(f"Unsupported file format: {file_name}")
except Exception as e:
logger.info(f"Error processing {file_name}: {str(e)}")
continue
return dfs
def create_table_from_dataframe_(self, df: pd.DataFrame, table_name: str, schema: str = 'csv_data'):
"""
Upload DataFrame to PostgreSQL, replacing NaN/null with empty string.
Args:
df (pd.DataFrame): Input DataFrame to upload
table_name (str): Destination table name
schema (str, optional): Database schema. Defaults to 'csv_data'.
"""
try:
# Sanitize column names
df = df.copy()
df.columns = [self.sanitize_column_name(col) for col in df.columns]
# Replace NaN and None with empty string
# df = df.fillna('')
# Write DataFrame to PostgreSQL
df.to_sql(
name=table_name,
con=self.engine,
schema=schema,
if_exists='replace', # Replace existing table
index=False, # Don't write index as a column
dtype=None # Let SQLAlchemy infer types
)
except Exception as e:
logger.error(f"Error uploading DataFrame to PostgreSQL: {e}")
raise
def extract_file_metadata(self, file_paths: List[str], ingestion_timestamps: List[str], uuid: str) -> pd.DataFrame:
"""
Extract metadata for multiple files and update in database using uuid as user_id.
If user exists, deletes all their existing records before inserting new ones.
Args:
file_paths (List[str]): List of paths to the files
ingestion_timestamps (List[str]): List of timestamps of ingestion
uuid (str): UUID for both user identification and file prefix
Returns:
pd.DataFrame: DataFrame containing metadata for all files
"""
try:
all_metadata_rows = []
for file_path, ingestion_timestamp in zip(file_paths, ingestion_timestamps):
try:
# Get file stats
stat_info = os.stat(file_path)
if file_path.endswith((".xlsx", ".xls")):
# Handle Excel files with multiple sheets
excel_file = pd.ExcelFile(file_path)
sheet_names = excel_file.sheet_names
for sheet_name in sheet_names:
df = pd.read_excel(file_path, sheet_name=sheet_name, nrows=5)
base_name = self.sanitize_column_name(os.path.basename(file_path[:-5]))
sheet_name_clean = self.sanitize_column_name(sheet_name)
table_name = f"{uuid}_{base_name}_{sheet_name_clean}"
if not df.empty:
all_metadata_rows.append({
'user_id': uuid,
'filename': table_name,
'sheet_name': sheet_name,
'file_path': file_path,
'file_size_bytes': stat_info.st_size,
'created_at': datetime.fromtimestamp(stat_info.st_ctime).strftime('%Y-%m-%d %H:%M:%S'),
'modified_at': datetime.fromtimestamp(stat_info.st_mtime).strftime('%Y-%m-%d %H:%M:%S'),
'ingested_at': ingestion_timestamp,
'num_columns': len(df.columns),
'columns': ', '.join(df.columns),
'first_5_rows': df.head().to_json(),
'file_type': 'excel'
})
elif file_path.endswith('csv'):
# Handle CSV files
df = pd.read_csv(file_path, nrows=5)
all_metadata_rows.append({
'user_id': uuid,
'filename': f"{uuid}_{self.sanitize_column_name(os.path.basename(file_path[:-4]))}",
'sheet_name': '',
'file_path': file_path,
'file_size_bytes': stat_info.st_size,
'created_at': datetime.fromtimestamp(stat_info.st_ctime).strftime('%Y-%m-%d %H:%M:%S'),
'modified_at': datetime.fromtimestamp(stat_info.st_mtime).strftime('%Y-%m-%d %H:%M:%S'),
'ingested_at': ingestion_timestamp,
'num_columns': len(df.columns),
'columns': ', '.join(df.columns),
'first_5_rows': df.head().to_json(),
'file_type': 'csv'
})
except Exception as e:
print(f"Error processing file {file_path}: {e}")
continue
if not all_metadata_rows:
print("No valid files were processed")
return None
# Create combined metadata DataFrame
metadata_df = pd.DataFrame(all_metadata_rows)
# Handle database operations
with self.engine.connect() as connection:
# Check if user exists
check_query = text("SELECT EXISTS(SELECT 1 FROM csv_data.file_metadata WHERE user_id = :user_id)")
result = connection.execute(check_query, {"user_id": uuid})
user_exists = result.scalar()
if user_exists:
# Delete all existing records for this user
delete_query = text("DELETE FROM csv_data.file_metadata WHERE user_id = :user_id")
connection.execute(delete_query, {"user_id": uuid})
# Insert all new records
metadata_df.to_sql('file_metadata',
connection,
schema='csv_data',
if_exists='append',
index=False)
connection.commit()
return metadata_df
except Exception as e:
print(f"Error in metadata extraction process: {e}")
return None
def dump_tableinfo(self, uploaded_path, uuid):
"""
Process and store table information for all data files.
Creates table summaries and maintains unique table names.
"""
self.table_infos = []
self.dfs = self.process_data(uploaded_path, uuid)
for idx, df in enumerate(self.dfs):
# Get sample of data for table summary
df_str = df.head(10).to_csv()
# Generate table info using LLM
table_info = self.program(
table_str=df_str,
table_name=self.table_names[idx],
)
table_name = table_info.table_name
logger.info(f"Processed table: {table_name}")
self.table_infos.append(table_info)
logger.info(f"Generated table info for {len(self.table_infos)} tables in csv_data schema")
def create_table(self, file_paths: list[str], uuid):
"""Create tables in PostgreSQL csv_data schema and handle metadata tracking.
Args:
file_paths: List of paths to files being processed
"""
logger.info("Creating tables in PostgreSQL csv_data schema")
create_table_query = """
CREATE TABLE IF NOT EXISTS csv_data.file_metadata (
user_id VARCHAR(255) NOT NULL,
filename VARCHAR(255) NOT NULL,
sheet_name VARCHAR(255),
file_path TEXT,
file_size_bytes BIGINT,
created_at TIMESTAMP,
modified_at TIMESTAMP,
ingested_at TIMESTAMP,
num_columns INTEGER,
columns TEXT,
first_5_rows JSONB,
file_type VARCHAR(50)
);
"""
with self.conn.cursor() as cursor:
cursor.execute(create_table_query)
self.conn.commit()
if isinstance(file_paths, str):
file_paths = [file_paths]
uuid_prefix = self.sanitize_query(uuid[:12])
self.dump_tableinfo(file_paths, uuid_prefix)
self.extract_file_metadata(
file_paths,
self.ingestion_timestamps,
uuid_prefix
)
file_metadata_tableinfo = TableInfo(
table_name="file_metadata",
table_summary="Metadata about processed files"
)
self.table_infos.append(file_metadata_tableinfo)
# try:
# self.table_names = []
# self.table_infos = []
# # Get list of tables in csv_data schema
# tables_query = """
# SELECT tablename
# FROM pg_catalog.pg_tables
# WHERE schemaname = 'csv_data';
# """
# with self.conn.cursor() as cursor:
# cursor.execute(tables_query)
# tables = cursor.fetchall()
# if not tables:
# print("No existing tables found in csv_data schema")
# return
# for table_data in tables:
# table_name = table_data[0]
# # Get sample data for table summary
# sample_query = f"""
# SELECT *
# FROM csv_data."{table_name}"
# LIMIT 10;
# """
# try:
# # Get column names
# cursor.execute(f"""
# SELECT column_name
# FROM information_schema.columns
# WHERE table_schema = 'csv_data'
# AND table_name = '{table_name}'
# """)
# columns = [col[0] for col in cursor.fetchall()]
# # Get sample data
# cursor.execute(sample_query)
# sample_data = cursor.fetchall()
# # Convert to DataFrame and then to CSV string
# import pandas as pd
# df_sample = pd.DataFrame(sample_data, columns=columns)
# df_str = df_sample.to_csv(index=False)
# while True:
# # Generate table info using LLM
# table_info = self.program(
# table_str=df_str,
# table_name=table_name
# )
# # generated_table_name = table_info.table_name
# print(f"Processed table: {table_info.table_name}")
# # Ensure table name is unique
# if table_info.table_name not in self.table_names:
# self.table_names.append(table_name)
# break
# else:
# print(f"Table name {table_name} already exists, trying again.")
# pass
# self.table_infos.append(table_info)
# except Exception as e:
# print(f"Warning: Error processing table {table_name}: {str(e)}")
# # Add basic table info if LLM summary fails
# fallback_table_info = TableInfo(
# table_name=table_name,
# table_summary=f"Table containing data from {table_name}"
# )
# self.table_infos.append(fallback_table_info)
# # print(self.table_infos)
# print(f"Successfully loaded {len(self.table_infos)} tables from csv_data schema:")
# except Exception as e:
# print(f"Error loading database schema: {str(e)}")
# self.table_infos = []
# raise
# finally:
# if hasattr(self, 'cur') and self.cur is not None:
# self.cur.close()
def load_existing_database(self):
"""
Retrieve existing database from PostgreSQL's csv_data schema and generate
table summaries using LLM.
"""
print("Retrieving existing database from PostgreSQL csv_data schema...")
try:
self.table_names = []
self.table_infos = []
# Get list of tables in csv_data schema
tables_query = """
SELECT tablename
FROM pg_catalog.pg_tables
WHERE schemaname = 'csv_data';
"""
with self.conn.cursor() as cur:
cur.execute(tables_query)
tables = cur.fetchall()
if not tables:
logger.info("No existing tables found in csv_data schema")
return
for table_data in tables:
table_name = table_data[0]
fallback_table_info = TableInfo(
table_name=table_name,
table_summary=f"Table containing data from {table_name}"
)
self.table_infos.append(fallback_table_info)
self.metadata_obj = MetaData()
self.metadata_obj.reflect(bind=self.engine, schema='csv_data')
logger.info(f"Successfully loaded {len(self.table_infos)} tables from csv_data schema")
except Exception as e:
logger.error(f"Error loading database schema: {str(e)}")
self.table_infos = []
raise