File size: 4,805 Bytes
116e2b2
af157d8
116e2b2
0981240
 
af157d8
 
75d5564
116e2b2
 
 
 
fe396c3
 
116e2b2
 
c640eb0
 
 
 
116e2b2
 
 
 
 
 
 
 
c640eb0
 
0981240
 
 
fe396c3
 
 
0eab4c2
 
 
fe396c3
 
 
0eab4c2
0981240
 
af157d8
116e2b2
 
fe396c3
116e2b2
 
fe396c3
116e2b2
 
 
fe396c3
116e2b2
 
 
 
 
 
fe396c3
116e2b2
af157d8
fe396c3
 
 
 
 
 
 
 
 
 
 
0eab4c2
 
 
 
 
fe396c3
0981240
af157d8
 
116e2b2
 
fe396c3
116e2b2
 
fe396c3
af157d8
 
 
 
8b50bab
 
 
af157d8
 
 
116e2b2
 
fe396c3
116e2b2
 
fe396c3
af157d8
fe396c3
af157d8
 
 
 
 
116e2b2
 
fe396c3
116e2b2
 
fe396c3
116e2b2
 
 
fe396c3
0981240
 
116e2b2
 
 
 
 
0981240
 
8b50bab
 
 
 
 
 
 
 
 
 
116e2b2
af157d8
 
 
fe396c3
 
 
 
a591cec
116e2b2
af157d8
8b50bab
 
 
 
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
"""RAG utilities — persistent ChromaDB with graceful fallback."""

import os
import uuid
import streamlit as st
from sentence_transformers import SentenceTransformer
import chromadb

# Storage directory for ChromaDB (persistent across calls, but not across Space restart)
CHROMA_PERSIST_DIR = "/tmp/secforge_chroma"
os.makedirs(CHROMA_PERSIST_DIR, exist_ok=True)

_chroma_client = None
_embedding_model_failed = False
_rag_enabled = True  # global flag to disable RAG after any fatal error


def _get_client():
    global _chroma_client
    if _chroma_client is None:
        try:
            # Use persistent client instead of ephemeral
            _chroma_client = chromadb.PersistentClient(path=CHROMA_PERSIST_DIR)
        except Exception as e:
            print(f"[RAG FATAL] Could not create ChromaDB client: {e}")
            global _rag_enabled
            _rag_enabled = False
            return None
    return _chroma_client


@st.cache_resource
def get_embedding_model():
    global _embedding_model_failed
    if _embedding_model_failed:
        return None
    try:
        return SentenceTransformer("all-MiniLM-L6-v2")
    except Exception as e:
        print(f"[RAG WARNING] Failed to load embedding model: {e}")
        print("[RAG WARNING] File uploads will work but semantic search will be disabled")
        _embedding_model_failed = True
        return None


def add_file(session_id: str, filename: str, text: str):
    if not _rag_enabled:
        return
    client = _get_client()
    if client is None:
        return
    model = get_embedding_model()
    if model is None:
        return

    collection_name = f"s{session_id[:32]}"
    try:
        # Get or create collection - use get_or_create_collection to avoid race conditions
        collection = client.get_or_create_collection(name=collection_name)
    except Exception as e:
        print(f"[RAG ERROR] Failed to get/create collection: {e}")
        return

    # Remove existing chunks for this file
    try:
        existing = collection.get(where={"source": filename})
        if existing["ids"]:
            collection.delete(ids=existing["ids"])
    except Exception:
        pass

    chunks = [line.strip() for line in text.split("\n") if line.strip()]
    if not chunks:
        return

    try:
        embeddings = model.encode(chunks).tolist()
        ids = [str(uuid.uuid4()) for _ in chunks]
        metadatas = [{"source": filename} for _ in chunks]
        collection.add(embeddings=embeddings, documents=chunks, ids=ids, metadatas=metadatas)
    except Exception as e:
        print(f"[RAG ERROR] Failed to add file {filename}: {e}")


def remove_file(session_id: str, filename: str):
    if not _rag_enabled:
        return
    client = _get_client()
    if client is None:
        return
    collection_name = f"s{session_id[:32]}"
    try:
        collection = client.get_collection(name=collection_name)
        existing = collection.get(where={"source": filename})
        if existing["ids"]:
            collection.delete(ids=existing["ids"])
    except Exception:
        pass


def clear_session(session_id: str):
    if not _rag_enabled:
        return
    client = _get_client()
    if client is None:
        return
    collection_name = f"s{session_id[:32]}"
    try:
        client.delete_collection(name=collection_name)
    except Exception:
        pass


def query_context(session_id: str, query: str, n_results: int = 8) -> str:
    if not _rag_enabled:
        return ""
    client = _get_client()
    if client is None:
        return ""
    model = get_embedding_model()
    if model is None:
        return ""

    collection_name = f"s{session_id[:32]}"
    try:
        collection = client.get_collection(name=collection_name)
    except Exception:
        # Collection does not exist – no context
        return ""

    try:
        count = collection.count()
        if count == 0:
            return ""
        actual_n = min(n_results, count)
        query_embedding = model.encode([query]).tolist()
        results = collection.query(
            query_embeddings=query_embedding,
            n_results=actual_n,
            include=["documents", "metadatas"],
        )
        docs = results["documents"][0]
        metas = results["metadatas"][0]
        grouped = {}
        for doc, meta in zip(docs, metas):
            src = meta.get("source", "unknown")
            grouped.setdefault(src, []).append(doc)
        parts = []
        for src, lines in grouped.items():
            parts.append(f"# from {src}\n" + "\n".join(lines))
        return "\n\n".join(parts)
    except Exception as e:
        print(f"[RAG ERROR] query failed: {e}")
        return ""


def add_document(collection_name: str, text: str):
    add_file(collection_name, "linked_file", text)