Spaces:
Sleeping
Sleeping
Fix module import issues and data loading bugs
Browse files- download_from_hub.py +2 -1
- embedder.py +90 -0
- src/__init__.py +2 -11
- src/models/retriever.py +13 -1
download_from_hub.py
CHANGED
|
@@ -4,7 +4,6 @@ import pickle
|
|
| 4 |
import sys
|
| 5 |
import numpy as np
|
| 6 |
from huggingface_hub import hf_hub_download, list_repo_files
|
| 7 |
-
from datasets import load_dataset
|
| 8 |
|
| 9 |
def ensure_dirs():
|
| 10 |
"""Create necessary directories if they don't exist."""
|
|
@@ -63,6 +62,7 @@ def download_datasets():
|
|
| 63 |
|
| 64 |
# Download embeddings
|
| 65 |
try:
|
|
|
|
| 66 |
print("Downloading embeddings...")
|
| 67 |
# First check what files are available in the dataset repository
|
| 68 |
try:
|
|
@@ -124,6 +124,7 @@ def download_datasets():
|
|
| 124 |
|
| 125 |
# Download document chunks
|
| 126 |
try:
|
|
|
|
| 127 |
print("Downloading document chunks...")
|
| 128 |
# First check what files are available
|
| 129 |
try:
|
|
|
|
| 4 |
import sys
|
| 5 |
import numpy as np
|
| 6 |
from huggingface_hub import hf_hub_download, list_repo_files
|
|
|
|
| 7 |
|
| 8 |
def ensure_dirs():
|
| 9 |
"""Create necessary directories if they don't exist."""
|
|
|
|
| 62 |
|
| 63 |
# Download embeddings
|
| 64 |
try:
|
| 65 |
+
from datasets import load_dataset
|
| 66 |
print("Downloading embeddings...")
|
| 67 |
# First check what files are available in the dataset repository
|
| 68 |
try:
|
|
|
|
| 124 |
|
| 125 |
# Download document chunks
|
| 126 |
try:
|
| 127 |
+
from datasets import load_dataset
|
| 128 |
print("Downloading document chunks...")
|
| 129 |
# First check what files are available
|
| 130 |
try:
|
embedder.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
from typing import List, Dict, Any, Optional
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
# Get API key from environment variable
|
| 9 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
|
| 10 |
+
EMBEDDING_MODEL = "text-embedding-3-small"
|
| 11 |
+
EMBEDDING_BATCH_SIZE = 10
|
| 12 |
+
|
| 13 |
+
class TextEmbedder:
|
| 14 |
+
"""Class for generating embeddings for document chunks using OpenAI's embeddings API."""
|
| 15 |
+
|
| 16 |
+
def __init__(self, model: str = EMBEDDING_MODEL, batch_size: int = EMBEDDING_BATCH_SIZE):
|
| 17 |
+
"""
|
| 18 |
+
Initialize the TextEmbedder with the specified embedding model and batch size.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
model: The OpenAI embedding model to use
|
| 22 |
+
batch_size: Number of chunks to embed per API call
|
| 23 |
+
"""
|
| 24 |
+
self.model = model
|
| 25 |
+
self.batch_size = batch_size
|
| 26 |
+
self.client = OpenAI(api_key=OPENAI_API_KEY)
|
| 27 |
+
self.embedding_dim = 1536 # Default dimension for text-embedding-3-small
|
| 28 |
+
|
| 29 |
+
def get_embedding_for_text(self, text: str) -> List[float]:
|
| 30 |
+
"""Generate embedding for a single text."""
|
| 31 |
+
try:
|
| 32 |
+
response = self.client.embeddings.create(
|
| 33 |
+
input=[text],
|
| 34 |
+
model=self.model
|
| 35 |
+
)
|
| 36 |
+
return response.data[0].embedding
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"Error generating embedding: {e}")
|
| 39 |
+
return [0.0] * self.embedding_dim
|
| 40 |
+
|
| 41 |
+
def get_embeddings_for_texts(self, texts: List[str]) -> List[List[float]]:
|
| 42 |
+
"""
|
| 43 |
+
Compute embeddings for a list of texts using batched API calls.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
texts: List of text chunks to embed
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
List of embedding vectors
|
| 50 |
+
"""
|
| 51 |
+
embeddings = []
|
| 52 |
+
for i in tqdm(range(0, len(texts), self.batch_size), desc="Embedding chunks"):
|
| 53 |
+
batch = texts[i:i + self.batch_size]
|
| 54 |
+
try:
|
| 55 |
+
response = self.client.embeddings.create(
|
| 56 |
+
input=batch,
|
| 57 |
+
model=self.model
|
| 58 |
+
)
|
| 59 |
+
# Extract embeddings from the response
|
| 60 |
+
for item in response.data:
|
| 61 |
+
embeddings.append(item.embedding)
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print(f"Error embedding batch starting at index {i}: {e}")
|
| 64 |
+
# Append placeholder zero vectors for failed texts
|
| 65 |
+
for _ in batch:
|
| 66 |
+
embeddings.append([0.0] * self.embedding_dim)
|
| 67 |
+
# Brief pause to avoid rate limits
|
| 68 |
+
time.sleep(0.2)
|
| 69 |
+
|
| 70 |
+
return embeddings
|
| 71 |
+
|
| 72 |
+
def get_query_embedding(self, query: str) -> np.ndarray:
|
| 73 |
+
"""
|
| 74 |
+
Generate embedding for a query string and return as numpy array.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
query: The query text to embed
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
Numpy array of the embedding
|
| 81 |
+
"""
|
| 82 |
+
try:
|
| 83 |
+
q_response = self.client.embeddings.create(
|
| 84 |
+
input=[query],
|
| 85 |
+
model=self.model
|
| 86 |
+
)
|
| 87 |
+
return np.array(q_response.data[0].embedding, dtype='float32').reshape(1, -1)
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"Error creating embedding for query: {e}")
|
| 90 |
+
return np.zeros((1, self.embedding_dim), dtype='float32')
|
src/__init__.py
CHANGED
|
@@ -1,13 +1,4 @@
|
|
| 1 |
"""Agentic Defensor - An agentic RAG system for legal defense analysis."""
|
| 2 |
|
| 3 |
-
#
|
| 4 |
-
|
| 5 |
-
from . import embeddings
|
| 6 |
-
from . import models
|
| 7 |
-
from . import agents
|
| 8 |
-
from . import utils
|
| 9 |
-
from . import data
|
| 10 |
-
from . import api
|
| 11 |
-
except ImportError as e:
|
| 12 |
-
import sys
|
| 13 |
-
print(f"Warning: Not all subpackages could be imported: {e}", file=sys.stderr)
|
|
|
|
| 1 |
"""Agentic Defensor - An agentic RAG system for legal defense analysis."""
|
| 2 |
|
| 3 |
+
# No explicit imports to avoid circular dependencies
|
| 4 |
+
# Each module will be imported directly where needed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/models/retriever.py
CHANGED
|
@@ -4,7 +4,19 @@ import numpy as np
|
|
| 4 |
from typing import List, Dict, Any, Tuple, Optional
|
| 5 |
|
| 6 |
from src.utils.config import TOP_K, FAISS_INDEX_PATH, DOC_CHUNKS_PATH
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
class Retriever:
|
| 10 |
"""
|
|
|
|
| 4 |
from typing import List, Dict, Any, Tuple, Optional
|
| 5 |
|
| 6 |
from src.utils.config import TOP_K, FAISS_INDEX_PATH, DOC_CHUNKS_PATH
|
| 7 |
+
|
| 8 |
+
# Try to import from the proper location, otherwise use the local copy
|
| 9 |
+
try:
|
| 10 |
+
from src.embeddings.embedder import TextEmbedder
|
| 11 |
+
except ImportError:
|
| 12 |
+
try:
|
| 13 |
+
import sys
|
| 14 |
+
import os
|
| 15 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 16 |
+
from embedder import TextEmbedder
|
| 17 |
+
print("Using local copy of embedder.py")
|
| 18 |
+
except ImportError as e:
|
| 19 |
+
print(f"Error importing TextEmbedder: {e}")
|
| 20 |
|
| 21 |
class Retriever:
|
| 22 |
"""
|