Upload 2 files
Browse files- .gitattributes +1 -0
- src/app.py +199 -0
- src/eu_policies.vxdf +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
src/eu_policies.vxdf filter=lfs diff=lfs merge=lfs -text
|
src/app.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Streamlit RAG demo: compare company policies against EU regulations.
|
| 2 |
+
|
| 3 |
+
Run with:
|
| 4 |
+
streamlit run use_case/app.py
|
| 5 |
+
|
| 6 |
+
Dependencies: streamlit, pdfplumber, sentence-transformers, openai (optional).
|
| 7 |
+
The app expects an EU policy VXDF file at ``use_case/eu_policies.vxdf``.
|
| 8 |
+
If an OpenAI key is set (env `OPENAI_API_KEY`) embeddings will default to
|
| 9 |
+
``text-embedding-3-large``; else falls back to ``all-MiniLM-L6-v2`` (local).
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import io
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import List, Any
|
| 18 |
+
|
| 19 |
+
from dotenv import load_dotenv
|
| 20 |
+
|
| 21 |
+
# Load environment variables from a .env file (if present)
|
| 22 |
+
load_dotenv()
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import streamlit as st
|
| 26 |
+
from numpy.typing import NDArray
|
| 27 |
+
|
| 28 |
+
from vxdf import VXDFReader
|
| 29 |
+
from vxdf.auth import get_openai_api_key
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
from sentence_transformers import SentenceTransformer # type: ignore
|
| 33 |
+
except ImportError: # pragma: no cover
|
| 34 |
+
SentenceTransformer = None # type: ignore
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
import openai # type: ignore
|
| 38 |
+
except ImportError: # pragma: no cover
|
| 39 |
+
openai = None # type: ignore
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
import pdfplumber # type: ignore
|
| 43 |
+
except ImportError: # pragma: no cover
|
| 44 |
+
pdfplumber = None # type: ignore
|
| 45 |
+
|
| 46 |
+
# ---------------------------------------------------------------------------
|
| 47 |
+
EU_VXDF_PATH = Path(__file__).with_suffix("").parent / "eu_policies.vxdf"
|
| 48 |
+
|
| 49 |
+
st.set_page_config(page_title="VXDF Compliance Checker", layout="wide")
|
| 50 |
+
st.title("📜🔍 EU Policy Compliance Checker")
|
| 51 |
+
|
| 52 |
+
# ---------------------------------------------------------------------------
|
| 53 |
+
@st.cache_resource(show_spinner="Loading EU policy database…")
|
| 54 |
+
def _load_vxdf(path: Path) -> tuple[List[str], NDArray[np.float32]]:
|
| 55 |
+
reader = VXDFReader(str(path))
|
| 56 |
+
ids = list(reader.offset_index.keys())
|
| 57 |
+
vecs = np.asarray([reader.get_chunk(cid)["vector"] for cid in ids], dtype=np.float32)
|
| 58 |
+
return ids, vecs
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _embed(sentences: List[str]) -> NDArray[np.float32]:
|
| 62 |
+
"""Embed sentences matching the reference embedding dimension (EU_DIM)."""
|
| 63 |
+
|
| 64 |
+
"""Embed sentences using OpenAI (v0 or v1 SDK) or local SentenceTransformer."""
|
| 65 |
+
api_key = get_openai_api_key()
|
| 66 |
+
# Prefer OpenAI embeddings when dims match EU_DIM and key available
|
| 67 |
+
if api_key and openai is not None and EU_DIM in {1536, 3072}:
|
| 68 |
+
try:
|
| 69 |
+
from openai import OpenAI # type: ignore
|
| 70 |
+
client: Any = OpenAI(api_key=api_key)
|
| 71 |
+
resp = client.embeddings.create(model="text-embedding-3-large", input=sentences)
|
| 72 |
+
vecs = np.asarray([d.embedding for d in resp.data], dtype=np.float32)
|
| 73 |
+
if vecs.shape[1] == EU_DIM:
|
| 74 |
+
return vecs
|
| 75 |
+
except Exception:
|
| 76 |
+
# fallthrough to local model
|
| 77 |
+
pass
|
| 78 |
+
# Local sentence-transformer fallback; choose model by target dim
|
| 79 |
+
if SentenceTransformer is None:
|
| 80 |
+
raise RuntimeError("sentence-transformers not installed. Install via `pip install sentence-transformers`. ")
|
| 81 |
+
st_model_map = {384: "all-MiniLM-L6-v2", 768: "all-mpnet-base-v2"}
|
| 82 |
+
model_name = st_model_map.get(EU_DIM, "all-MiniLM-L6-v2")
|
| 83 |
+
model = SentenceTransformer(model_name)
|
| 84 |
+
return model.encode(sentences, normalize_embeddings=True)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _similarity(a: NDArray[np.float32], b: NDArray[np.float32]) -> NDArray[np.float32]:
|
| 88 |
+
# cosine sim since vectors are normalized
|
| 89 |
+
return np.dot(a, b.T)
|
| 90 |
+
|
| 91 |
+
# ---------------------------------------------------------------------------
|
| 92 |
+
if not EU_VXDF_PATH.exists():
|
| 93 |
+
st.error(
|
| 94 |
+
f"EU policy VXDF not found at {EU_VXDF_PATH}. Please place the file there and restart the app.")
|
| 95 |
+
st.stop()
|
| 96 |
+
|
| 97 |
+
EU_IDS, EU_VECS = _load_vxdf(EU_VXDF_PATH)
|
| 98 |
+
EU_DIM = EU_VECS.shape[1] # reference embedding dimension
|
| 99 |
+
|
| 100 |
+
# Sidebar: upload company policy PDF or paste text -------------------------------------------------
|
| 101 |
+
with st.sidebar:
|
| 102 |
+
st.header("Company Policy Input")
|
| 103 |
+
uploaded = st.file_uploader("Upload PDF", type=["pdf"])
|
| 104 |
+
pasted_text = st.text_area("…or paste policy text here", height=200)
|
| 105 |
+
|
| 106 |
+
def _pdf_to_paragraphs(data: bytes) -> List[str]:
|
| 107 |
+
if pdfplumber is None:
|
| 108 |
+
st.warning("pdfplumber not installed; can't parse PDF.")
|
| 109 |
+
return []
|
| 110 |
+
paras: List[str] = []
|
| 111 |
+
with pdfplumber.open(io.BytesIO(data)) as pdf:
|
| 112 |
+
for page in pdf.pages:
|
| 113 |
+
txt = page.extract_text() or ""
|
| 114 |
+
for para in txt.split("\n\n"):
|
| 115 |
+
para = para.strip()
|
| 116 |
+
if para:
|
| 117 |
+
paras.append(para)
|
| 118 |
+
return paras
|
| 119 |
+
|
| 120 |
+
company_paras: List[str] = []
|
| 121 |
+
if uploaded is not None:
|
| 122 |
+
company_paras.extend(_pdf_to_paragraphs(uploaded.read()))
|
| 123 |
+
if pasted_text.strip():
|
| 124 |
+
company_paras.append(pasted_text.strip())
|
| 125 |
+
|
| 126 |
+
if company_paras:
|
| 127 |
+
comp_vecs = _embed(company_paras)
|
| 128 |
+
else:
|
| 129 |
+
comp_vecs = np.zeros((0, EU_VECS.shape[1]), dtype=np.float32)
|
| 130 |
+
|
| 131 |
+
# Main chat interface -----------------------------------------------------------------------------
|
| 132 |
+
if "messages" not in st.session_state:
|
| 133 |
+
st.session_state.messages = []
|
| 134 |
+
|
| 135 |
+
for msg in st.session_state.messages:
|
| 136 |
+
with st.chat_message(msg["role"]):
|
| 137 |
+
st.markdown(msg["content"])
|
| 138 |
+
|
| 139 |
+
prompt = st.chat_input("Ask about compliance…")
|
| 140 |
+
if prompt:
|
| 141 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 142 |
+
with st.chat_message("user"):
|
| 143 |
+
st.markdown(prompt)
|
| 144 |
+
|
| 145 |
+
# ---- RAG: embed query, search EU and company docs -----------------------
|
| 146 |
+
q_vec = _embed([prompt])[0]
|
| 147 |
+
sims_eu = _similarity(q_vec.reshape(1, -1), EU_VECS)[0]
|
| 148 |
+
top_idx = np.argsort(sims_eu)[-3:][::-1]
|
| 149 |
+
eu_hits = [(EU_IDS[i], sims_eu[i]) for i in top_idx]
|
| 150 |
+
|
| 151 |
+
context_chunks: List[str] = []
|
| 152 |
+
reader = VXDFReader(str(EU_VXDF_PATH))
|
| 153 |
+
for cid, score in eu_hits:
|
| 154 |
+
chunk = reader.get_chunk(cid)
|
| 155 |
+
context_chunks.append(f"EU:{cid} (score {score:.2f}): {chunk['text']}")
|
| 156 |
+
|
| 157 |
+
if comp_vecs.shape[0]:
|
| 158 |
+
sims_comp = _similarity(q_vec.reshape(1, -1), comp_vecs)[0]
|
| 159 |
+
best_idx = int(np.argmax(sims_comp))
|
| 160 |
+
best_score = float(sims_comp[best_idx])
|
| 161 |
+
context_chunks.append(f"COMPANY (score {best_score:.2f}): {company_paras[best_idx][:300]}")
|
| 162 |
+
|
| 163 |
+
context = "\n---\n".join(context_chunks)
|
| 164 |
+
|
| 165 |
+
# Generate answer --------------------------------------------------------
|
| 166 |
+
answer: str
|
| 167 |
+
api_key = get_openai_api_key()
|
| 168 |
+
if api_key and openai is not None:
|
| 169 |
+
try:
|
| 170 |
+
from openai import OpenAI # type: ignore
|
| 171 |
+
|
| 172 |
+
client: Any = OpenAI(api_key=api_key)
|
| 173 |
+
resp = client.chat.completions.create(
|
| 174 |
+
model="gpt-3.5-turbo",
|
| 175 |
+
messages=[
|
| 176 |
+
{"role": "system", "content": "You are a compliance assistant referencing EU regulations."},
|
| 177 |
+
{"role": "user", "content": f"Context:\n{context}\n\nQuestion:{prompt}"},
|
| 178 |
+
],
|
| 179 |
+
temperature=0.2,
|
| 180 |
+
)
|
| 181 |
+
answer = resp.choices[0].message.content.strip()
|
| 182 |
+
except (ImportError, AttributeError):
|
| 183 |
+
openai.api_key = api_key # type: ignore
|
| 184 |
+
resp = openai.ChatCompletion.create( # type: ignore
|
| 185 |
+
model="gpt-3.5-turbo",
|
| 186 |
+
messages=[
|
| 187 |
+
{"role": "system", "content": "You are a compliance assistant referencing EU regulations."},
|
| 188 |
+
{"role": "user", "content": f"Context:\n{context}\n\nQuestion:{prompt}"},
|
| 189 |
+
],
|
| 190 |
+
temperature=0.2,
|
| 191 |
+
)
|
| 192 |
+
answer = resp["choices"][0]["message"]["content"].strip()
|
| 193 |
+
else:
|
| 194 |
+
# Fallback: simple extractive answer = top match text
|
| 195 |
+
answer = "\n\n".join(context_chunks[:2])
|
| 196 |
+
|
| 197 |
+
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 198 |
+
with st.chat_message("assistant"):
|
| 199 |
+
st.markdown(answer)
|
src/eu_policies.vxdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8806e7d94659fe8b69917fd661a79abaf00fa65f144ba5730db61a27a17d7d59
|
| 3 |
+
size 7278889
|