phaethon-order commited on
Commit
956db16
·
unverified ·
1 Parent(s): bb0de15

Refactor configuration and file handling for improved directory management and fallback mechanisms

Browse files
config.py CHANGED
@@ -15,24 +15,8 @@ class Config:
15
  TOP_K_RESULTS = os.getenv("TOP_K_RESULTS")
16
  MAX_QUERY_LENGTH = os.getenv("MAX_QUERY_LENGTH")
17
  REQUEST_TIMEOUT = os.getenv("REQUEST_TIMEOUT")
18
- UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER", "gs://tx-rag-corpus/corpus_raw")
19
- CLEAN_FOLDER = os.getenv("CLEAN_FOLDER", "gs://tx-rag-corpus/corpus_clean")
20
- METADATA_FOLDER = os.getenv("METADATA_FOLDER", "gs://tx-rag-corpus/manifest")
21
- CHUNKS_FOLDER = os.getenv("CHUNKS_FOLDER", "gs://tx-rag-corpus/chunks")
22
- DB_PATH = os.getenv("DB_PATH", "gs://tx-rag-corpus/app.db")
23
- DB_NAME = os.getenv("DB_NAME", "appdb")
24
- DB_USER = os.getenv("DB_USER", "appuser")
25
- DB_PASSWORD = os.getenv("DB_PASSWORD", "appuser")
26
- DB_HOST = os.getenv("DB_HOST", "10.25.1.3")
27
- DB_PORT = os.getenv("DB_PORT", "5432")
28
- CLOUD_SQL_CONNECTION_NAME = os.getenv("CLOUD_SQL_CONNECTION_NAME", "tech-trans-rag:us-west2:tx-rag-pg")
29
- DB_IAM_AUTH=os.getenv("DB_IAM_AUTH", "False").lower() in ("true", "1", "t")
30
- DB_USE_CONNECTOR=os.getenv("DB_USE_CONNECTOR", "False").lower() in ("true", "1", "t")
31
- VERTEX_PROJECT_ID = os.getenv("VERTEX_PROJECT_ID", "tech-trans-rag")
32
- VERTEX_LOCATION = os.getenv("VERTEX_LOCATION", "us-west2")
33
- VERTEX_INDEX_ENDPOINT_ID = os.getenv("VERTEX_INDEX_ENDPOINT_ID", "6972425444192681984")
34
- VERTEX_INDEX_ID = os.getenv("VERTEX_INDEX_ID", "9085431706080509952")
35
- VERTEX_DEPLOYED_INDEX_ID = os.getenv("VERTEX_DEPLOYED_INDEX_ID", "chunks_deployed")
36
 
37
  def cfg(key, default=None, cast=lambda x: x):
38
  val = current_app.config.get(key) if has_app_context() else None
 
15
  TOP_K_RESULTS = os.getenv("TOP_K_RESULTS")
16
  MAX_QUERY_LENGTH = os.getenv("MAX_QUERY_LENGTH")
17
  REQUEST_TIMEOUT = os.getenv("REQUEST_TIMEOUT")
18
+
19
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  def cfg(key, default=None, cast=lambda x: x):
22
  val = current_app.config.get(key) if has_app_context() else None
infrastructure/chunker.py CHANGED
@@ -45,12 +45,9 @@ except Exception: # pragma: no cover - fallback path
45
  logger = get_logger()
46
 
47
  API_KEY = os.getenv("OPENAI_API_KEY", "")
 
 
48
 
49
- API_KEY = os.getenv("OPENAI_API_KEY")
50
- PROJECT_ID = os.getenv("VERTEX_PROJECT_ID", "tech-trans-rag")
51
- GCS_BUCKET = os.getenv("GCS_BUCKET", "tech-trans-rag-bucket")
52
- MANIFEST_DOC = os.getenv("MANIFEST_DOC", "manifest/manifest.jsonl")
53
- CHUNKS_DOC = os.getenv("CHUNKS_DOC", "chunks/chunks.jsonl")
54
 
55
 
56
  def _split_pages(text: str) -> List[str]:
@@ -367,18 +364,19 @@ def chunk_doc(text: str, doc_id: str, max_chars: int = 1200, overlap: int = 150,
367
  rec['next_id'] = chunk_metadata_records[i+1]['index']
368
 
369
  # Write / upsert JSONL file
370
- os.makedirs(os.path.dirname(CHUNKS_DOC), exist_ok=True)
371
  records = json.dumps(chunk_metadata_records, ensure_ascii=False, indent=0)
 
372
 
373
  try:
374
- with open(CHUNKS_DOC, "r+", encoding="utf-8") as f:
375
  existing = f.read()
376
  f.seek(0)
377
  updated = existing + "\n" + records if existing else records
378
  f.write(updated)
379
- logger.info(f"Appended {len(chunk_metadata_records)} chunk records to existing chunks file {CHUNKS_DOC}")
380
  except FileNotFoundError:
381
- with open(CHUNKS_DOC, "w", encoding="utf-8") as f:
382
  f.write(records)
383
  logger.info(f"Created new chunks file with {len(chunk_metadata_records)} records as it did not exist")
384
 
 
45
  logger = get_logger()
46
 
47
  API_KEY = os.getenv("OPENAI_API_KEY", "")
48
+ CHUNKS_DIR = os.getenv("CHUNKS_DIR", "/data/chunks")
49
+
50
 
 
 
 
 
 
51
 
52
 
53
  def _split_pages(text: str) -> List[str]:
 
364
  rec['next_id'] = chunk_metadata_records[i+1]['index']
365
 
366
  # Write / upsert JSONL file
367
+ os.makedirs(os.path.dirname(CHUNKS_DIR), exist_ok=True)
368
  records = json.dumps(chunk_metadata_records, ensure_ascii=False, indent=0)
369
+ path = os.path.join(CHUNKS_DIR, "chunks.jsonl")
370
 
371
  try:
372
+ with open(path, "r+", encoding="utf-8") as f:
373
  existing = f.read()
374
  f.seek(0)
375
  updated = existing + "\n" + records if existing else records
376
  f.write(updated)
377
+ logger.info(f"Appended {len(chunk_metadata_records)} chunk records to existing chunks file {path}")
378
  except FileNotFoundError:
379
+ with open(path, "w", encoding="utf-8") as f:
380
  f.write(records)
381
  logger.info(f"Created new chunks file with {len(chunk_metadata_records)} records as it did not exist")
382
 
infrastructure/database.py CHANGED
@@ -8,7 +8,6 @@ from dataclasses import dataclass, field, fields
8
  from typing import List, Optional, Dict, Any
9
  import numpy as np
10
 
11
- import chromadb
12
  from chromadb.utils import embedding_functions
13
 
14
  try:
@@ -26,10 +25,47 @@ TOK_VER = int(os.getenv("TOK_VER", "1"))
26
  SEG_VER = int(os.getenv("SEG_VER", "1"))
27
 
28
  # ---------------------------------------------------------------------------
29
- # ChromaDB client setup
30
  # ---------------------------------------------------------------------------
31
  CHROMA_PATH = os.getenv("CHROMA_PATH", "chroma_db")
32
- _client = chromadb.PersistentClient(path=CHROMA_PATH)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  # Using a default embedding function for the collections, though we'll be providing our own embeddings.
35
  # This is required by ChromaDB.
 
8
  from typing import List, Optional, Dict, Any
9
  import numpy as np
10
 
 
11
  from chromadb.utils import embedding_functions
12
 
13
  try:
 
25
  SEG_VER = int(os.getenv("SEG_VER", "1"))
26
 
27
  # ---------------------------------------------------------------------------
28
+ # ChromaDB client setup (with HuggingFace / read-only filesystem resilience)
29
  # ---------------------------------------------------------------------------
30
  CHROMA_PATH = os.getenv("CHROMA_PATH", "chroma_db")
31
+
32
+ def _init_chroma_client():
33
+ """Initialize a Chroma client with fallbacks.
34
+
35
+ Order of attempts:
36
+ 1. Provided/ default CHROMA_PATH (relative or absolute)
37
+ 2. /tmp/chroma_db (writable in most containerized envs incl. HF Spaces)
38
+ 3. In-memory (non-persistent) client as last resort
39
+ """
40
+ candidates: list[Optional[str]] = [CHROMA_PATH, "/tmp/chroma_db", None]
41
+ tried: list[tuple[Optional[str], str]] = []
42
+
43
+ for cand in candidates:
44
+ try:
45
+ if cand is None:
46
+ _logger.warning("ChromaDB falling back to in-memory client (no persistence).")
47
+ import chromadb
48
+ return chromadb.Client() # type: ignore
49
+ # Ensure directory exists and is writable
50
+ abs_path = os.path.abspath(cand)
51
+ os.makedirs(abs_path, exist_ok=True)
52
+ test_file = os.path.join(abs_path, ".write_test")
53
+ with open(test_file, "w", encoding="utf-8") as tf:
54
+ tf.write("ok")
55
+ os.remove(test_file)
56
+ _logger.info(f"Initializing Chroma PersistentClient at {abs_path}")
57
+ import chromadb
58
+ return chromadb.PersistentClient(path=abs_path) # type: ignore
59
+ except Exception as e: # pragma: no cover - environment specific
60
+ tried.append((cand, str(e)))
61
+ # Continue to next candidate
62
+ continue
63
+
64
+ _logger.error("Failed to initialize persistent Chroma client; attempts=%s. Using in-memory fallback.", tried)
65
+ import chromadb
66
+ return chromadb.Client() # type: ignore
67
+
68
+ _client = _init_chroma_client()
69
 
70
  # Using a default embedding function for the collections, though we'll be providing our own embeddings.
71
  # This is required by ChromaDB.
infrastructure/document_processor.py CHANGED
@@ -16,10 +16,8 @@ from datetime import datetime, timezone
16
  logger = get_logger()
17
 
18
  API_KEY = os.getenv("OPENAI_API_KEY")
19
- PROJECT_ID = os.getenv("VERTEX_PROJECT_ID", "tech-trans-rag")
20
- GCS_BUCKET = os.getenv("GCS_BUCKET", "tech-trans-rag-bucket")
21
- MANIFEST_DOC = os.getenv("MANIFEST_DOC", "manifest/manifest.jsonl")
22
- CHUNKS_DOC = os.getenv("CHUNKS_DOC", "chunks/chunks.jsonl")
23
 
24
  def ocr_page(page: fitz.Page, zoom: float = 2.0) -> str:
25
  mat = fitz.Matrix(zoom, zoom)
@@ -262,10 +260,10 @@ def upsert_manifest_record(text: str, size: str, doc_id: str, sha256: str, sourc
262
  }
263
 
264
  line = json.dumps(manifest_record) + "\n"
265
- manifest_path = MANIFEST_DOC
266
 
267
  try:
268
- os.makedirs(os.path.dirname(manifest_path), exist_ok=True)
269
 
270
  with open(manifest_path, "a", encoding="utf-8") as f:
271
  f.write(line)
 
16
  logger = get_logger()
17
 
18
  API_KEY = os.getenv("OPENAI_API_KEY")
19
+ MANIFEST_DIR = os.getenv("MANIFEST_DIR", "data/manifest")
20
+ CHUNKS_DIR = os.getenv("CHUNKS_DIR", "data/chunks")
 
 
21
 
22
  def ocr_page(page: fitz.Page, zoom: float = 2.0) -> str:
23
  mat = fitz.Matrix(zoom, zoom)
 
260
  }
261
 
262
  line = json.dumps(manifest_record) + "\n"
263
+ manifest_path = MANIFEST_DIR + "/manifest.jsonl"
264
 
265
  try:
266
+ os.makedirs(os.path.dirname(MANIFEST_DIR), exist_ok=True)
267
 
268
  with open(manifest_path, "a", encoding="utf-8") as f:
269
  f.write(line)
routes/api.py CHANGED
@@ -26,8 +26,8 @@ api_bp = Blueprint("api", __name__, url_prefix="/api")
26
  logger = get_logger()
27
 
28
  ALLOWED_EXTENSIONS = {"pdf", "docx", "txt"}
29
- UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER", "corpus_raw/")
30
- CLEAN_FOLDER = os.getenv("CLEAN_FOLDER", "corpus_clean/")
31
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
32
  os.makedirs(CLEAN_FOLDER, exist_ok=True)
33
 
 
26
  logger = get_logger()
27
 
28
  ALLOWED_EXTENSIONS = {"pdf", "docx", "txt"}
29
+ UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER", "/data/corpus_raw")
30
+ CLEAN_FOLDER = os.getenv("CLEAN_FOLDER", "/data/corpus_clean")
31
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
32
  os.makedirs(CLEAN_FOLDER, exist_ok=True)
33