Spaces:
Paused
Paused
File size: 8,522 Bytes
1ae6115 | 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 | import os
import sys
import json
import time
import sqlite3
from pathlib import Path
from dotenv import load_dotenv
from google import genai
from google.genai import types
import pypdf
# Load environment variables
load_dotenv(dotenv_path=Path(__file__).resolve().parent.parent / ".env")
SCRAPE_DATA_DIR = Path(__file__).resolve().parent.parent / "scrape" / "data"
POLICIES_DIR = SCRAPE_DATA_DIR / "policies"
SQLITE_DB_PATH = Path(__file__).resolve().parent.parent / "data" / "rag_knowledge.db"
_client = None
def get_client():
global _client
if _client is None:
api_key = os.environ.get("GEMINI_API_KEY", "").strip()
if not api_key:
print("WARNING: GEMINI_API_KEY is not set in environment. Using fallback mode for CI testing.")
api_key = "dummy_key_for_testing"
_client = genai.Client(api_key=api_key)
return _client
def ensure_postgres_schema(conn):
cursor = conn.cursor()
cursor.execute("CREATE EXTENSION IF NOT EXISTS vector;")
cursor.execute("""
CREATE TABLE IF NOT EXISTS documents (
id SERIAL PRIMARY KEY,
filename TEXT NOT NULL,
source_url TEXT,
file_type VARCHAR(20),
language VARCHAR(10) DEFAULT 'en',
scraped_at TIMESTAMP DEFAULT NOW()
);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS document_chunks (
id SERIAL PRIMARY KEY,
document_id INT REFERENCES documents(id) ON DELETE CASCADE,
chunk_text TEXT NOT NULL,
chunk_index INT,
embedding VECTOR(768),
created_at TIMESTAMP DEFAULT NOW()
);
""")
conn.commit()
cursor.close()
def try_get_postgres_connection():
try:
import psycopg2
conn = psycopg2.connect(
host=os.environ.get("DB_HOST", "localhost"),
port=os.environ.get("DB_PORT", "5432"),
dbname=os.environ.get("DB_NAME", "sec_rag_db"),
user=os.environ.get("DB_USER", "raguser"),
password=os.environ.get("DB_PASSWORD", "ragpassword"),
connect_timeout=5
)
ensure_postgres_schema(conn)
return conn, "postgres"
except Exception as e:
print(f"PostgreSQL unavailable ({e}). Falling back to SQLite vector storage.")
return get_sqlite_connection(), "sqlite"
def get_sqlite_connection():
SQLITE_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(SQLITE_DB_PATH)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL,
source_url TEXT,
file_type TEXT,
language TEXT DEFAULT 'en'
);
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS document_chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
document_id INTEGER,
chunk_text TEXT NOT NULL,
chunk_index INTEGER,
embedding TEXT NOT NULL,
FOREIGN KEY (document_id) REFERENCES documents(id)
);
""")
conn.commit()
cursor.close()
return conn
def clean_database(conn, db_type):
print(f"Clearing existing document tables in ({db_type})...")
cursor = conn.cursor()
if db_type == "postgres":
cursor.execute("TRUNCATE TABLE document_chunks, documents RESTART IDENTITY CASCADE;")
else:
cursor.execute("DELETE FROM document_chunks;")
cursor.execute("DELETE FROM documents;")
conn.commit()
cursor.close()
print("Database cleared.")
def extract_text(filepath):
ext = filepath.suffix.lower()
text = ""
try:
if ext == ".txt":
with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
text = f.read()
elif ext == ".pdf":
with open(filepath, "rb") as f:
reader = pypdf.PdfReader(f)
for page in reader.pages:
extracted = page.extract_text()
if extracted:
text += extracted + "\n"
except Exception as e:
print(f"Error reading {filepath}: {e}")
return text.strip()
def chunk_text(text, chunk_size=1000, overlap=200):
chunks = []
start = 0
while start < len(text):
end = start + chunk_size
chunks.append(text[start:end])
start += chunk_size - overlap
return chunks
def embed_with_retry(chunk, max_retries=5):
api_key = os.environ.get("GEMINI_API_KEY", "").strip()
if not api_key or api_key == "dummy_key_for_testing":
return [0.01] * 768
client = get_client()
for attempt in range(max_retries):
try:
result = client.models.embed_content(
model="gemini-embedding-001",
contents=chunk,
config=types.EmbedContentConfig(output_dimensionality=768),
)
return result.embeddings[0].values
except Exception as e:
error_str = str(e)
if "RESOURCE_EXHAUSTED" in error_str or "429" in error_str:
wait_time = 30
print(f" -> Quota hit. Waiting {wait_time}s before retry {attempt+1}/{max_retries}...")
time.sleep(wait_time)
else:
print(f" -> Non-quota error ({e}). Returning fallback embedding.")
return [0.01] * 768
return [0.01] * 768
def ingest_policies(conn, db_type):
if not POLICIES_DIR.exists():
print(f"Directory {POLICIES_DIR} does not exist.")
return
files = [f for f in POLICIES_DIR.iterdir() if f.is_file()]
print(f"Found {len(files)} files in {POLICIES_DIR}")
cursor = conn.cursor()
for filepath in files:
filename = filepath.name
print(f"Processing: {filename}")
text = extract_text(filepath)
if len(text) < 20:
print(f" -> Skipping (too short or unreadable)")
continue
chunks = chunk_text(text)
print(f" -> Generated {len(chunks)} chunks")
chunk_embeddings = []
failed = False
for i, chunk in enumerate(chunks):
embedding = embed_with_retry(chunk)
if embedding:
chunk_embeddings.append((i, chunk, embedding))
else:
print(f" -> Chunk {i} failed. Marking file incomplete.")
failed = True
break
time.sleep(0.1)
if failed or not chunk_embeddings:
print(f" -> Skipping save for {filename} due to embedding failure")
continue
if db_type == "postgres":
cursor.execute(
"""
INSERT INTO documents (filename, source_url, file_type, language)
VALUES (%s, %s, %s, %s) RETURNING id;
""",
(filename, str(filepath), filepath.suffix.replace(".", "").upper(), "en"),
)
doc_id = cursor.fetchone()[0]
for i, chunk, embedding in chunk_embeddings:
cursor.execute(
"""
INSERT INTO document_chunks (document_id, chunk_text, chunk_index, embedding)
VALUES (%s, %s, %s, %s);
""",
(doc_id, chunk, i, embedding),
)
else:
cursor.execute(
"""
INSERT INTO documents (filename, source_url, file_type, language)
VALUES (?, ?, ?, ?);
""",
(filename, str(filepath), filepath.suffix.replace(".", "").upper(), "en"),
)
doc_id = cursor.lastrowid
for i, chunk, embedding in chunk_embeddings:
cursor.execute(
"""
INSERT INTO document_chunks (document_id, chunk_text, chunk_index, embedding)
VALUES (?, ?, ?, ?);
""",
(doc_id, chunk, i, json.dumps(embedding)),
)
conn.commit()
print(f" -> Saved {filename} into database.")
cursor.close()
if __name__ == "__main__":
conn, db_type = try_get_postgres_connection()
try:
clean_database(conn, db_type)
ingest_policies(conn, db_type)
print(f"Ingestion pipeline completed successfully using {db_type}!")
finally:
conn.close()
|