Spaces:
Runtime error

File size: 9,233 Bytes
747ecf5
d493ba6
 
 
 
 
 
 
 
 
747ecf5
 
 
 
e7d4287
747ecf5
 
 
2dec720
747ecf5
b2f92c4
2dec720
747ecf5
 
 
 
c6d7c61
747ecf5
 
 
e7d4287
00a3831
 
 
 
 
 
 
e7d4287
c6d7c61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747ecf5
 
 
 
 
 
 
 
 
 
d493ba6
 
 
 
747ecf5
b2f92c4
 
 
 
 
 
 
2dec720
 
 
 
 
 
 
 
 
747ecf5
 
 
2dec720
747ecf5
 
2dec720
 
 
 
2a25214
2dec720
747ecf5
 
2dec720
747ecf5
 
2dec720
 
747ecf5
 
 
 
2dec720
747ecf5
2dec720
 
747ecf5
2dec720
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747ecf5
2dec720
 
 
 
 
 
 
 
 
 
 
 
 
 
2a25214
2dec720
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a25214
2dec720
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a25214
2dec720
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747ecf5
 
 
 
 
 
 
 
 
 
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import os
import sys

# Fix for ChromaDB sqlite version issues (must be before other imports)
try:
    __import__('pysqlite3')
    sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
except ImportError:
    pass

import uvicorn
import shutil
from dotenv import load_dotenv
from fastapi import FastAPI, Depends, HTTPException, UploadFile, File, Form, Security, status
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
import database as db
from dependencies import get_db, get_api_client
from website_chat_router import chat_router
from admin_router import router as admin_router
from process_client_docs import process_client_document, calculate_file_hash

# --- Load Environment Variables ---
load_dotenv()

# --- FastAPI App Initialization ---
# --- FastAPI App Initialization ---
app = FastAPI()

# Mount static images directory
try:
    images_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "images")
    os.makedirs(images_dir, exist_ok=True)
    app.mount("/images", StaticFiles(directory=images_dir), name="images")
    print(f"βœ… Mounted /images pointing to: {images_dir}")
except Exception as e:
    print(f"❌ Failed to mount /images: {e}")

@app.on_event("startup")
async def startup_event():
    """
    On startup, check if the persistent volume is empty.
    If so, seed it with the data from the Docker image.
    """
    data_dir = "data"
    seed_dir = "/app/data_seed" # Absolute path in Docker container
    
    # Only run if seed directory exists (i.e., in Docker)
    if os.path.exists(seed_dir):
        print(f"πŸ” Checking if seeding is needed from {seed_dir}...")
        
        # Ensure data dir exists
        os.makedirs(data_dir, exist_ok=True)
        
        # Check for users.db
        target_db = os.path.join(data_dir, "users.db")
        if not os.path.exists(target_db):
            print("πŸ“¦ Seeding users.db...")
            shutil.copy2(os.path.join(seed_dir, "users.db"), target_db)
            
        # Check for vectorstores
        seed_vs = os.path.join(seed_dir, "vectorstores_client")
        target_vs = os.path.join(data_dir, "vectorstores_client")
        
        if os.path.exists(seed_vs) and not os.path.exists(target_vs):
            print("πŸ“¦ Seeding vectorstores...")
            shutil.copytree(seed_vs, target_vs, dirs_exist_ok=True)
            
        print("βœ… Startup checks complete.")

# --- CORS Middleware ---
origins = ["*"] # Allow all for a public API, or restrict as needed
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def health_check():
    return {"status": "ok", "message": "NutriBot API is running"}

# --- API Routers ---
# Admin router (no authentication required - uses password in the form)
app.include_router(
    admin_router,
    prefix="/admin",
    tags=["Admin"]
)

# Client portal router (session-based authentication)
from client_portal_router import router as portal_router
app.include_router(
    portal_router,
    prefix="/portal",
    tags=["Client Portal"]
)

# The chat router endpoints handle authentication individually
app.include_router(
    chat_router, 
    prefix="/chat", 
    tags=["Chat"]
)

# --- NEW: Batch File Upload Endpoint ---
@app.post("/upload_documents/", tags=["Document Upload"])
async def upload_documents(
    files: list[UploadFile] = File(...),
    client = Depends(get_api_client),
    database: Session = Depends(get_db)
):
    """
    Endpoint for B2B clients to upload multiple documents for their knowledge base.
    Requires a valid 'X-API-Key' in the header.
    """
    from process_client_docs import process_client_document, calculate_file_hash
    
    # Create a temporary directory to store uploaded files
    temp_dir = "temp_uploads"
    os.makedirs(temp_dir, exist_ok=True)
    
    results = []
    
    for file in files:
        temp_filepath = os.path.join(temp_dir, file.filename)
        
        try:
            # Save the uploaded file temporarily
            with open(temp_filepath, "wb") as buffer:
                shutil.copyfileobj(file.file, buffer)
            
            # Calculate file hash for deduplication
            file_hash = calculate_file_hash(temp_filepath)
            file_size = os.path.getsize(temp_filepath)
            
            # Check if document already exists for this client
            existing_doc = db.get_document_by_hash(database, client.id, file_hash)
            if existing_doc:
                results.append({
                    "filename": file.filename,
                    "status": "skipped",
                    "message": "Document already exists (duplicate)"
                })
                os.remove(temp_filepath)
                continue
            
            # Process the document
            process_result = process_client_document(
                client_id=client.id, 
                filepath=temp_filepath, 
                filename=file.filename
            )
            
            # Add document metadata to database
            doc_metadata = db.add_document_metadata(
                database,
                client_id=client.id,
                filename=file.filename,
                file_hash=process_result["file_hash"],
                file_size=file_size,
                chunk_count=process_result["chunk_count"],
                status=process_result["status"]
            )
            
            results.append({
                "filename": file.filename,
                "document_id": doc_metadata.id,
                "status": process_result["status"],
                "chunk_count": process_result["chunk_count"],
                "file_size": file_size
            })
            
        except Exception as e:
            results.append({
                "filename": file.filename,
                "status": "failed",
                "error": str(e)
            })
        
        finally:
            # Clean up the temporary file
            if os.path.exists(temp_filepath):
                os.remove(temp_filepath)
    
    return {
        "client_name": client.client_name,
        "total_files": len(files),
        "results": results
    }

# --- NEW: Document Management Endpoints ---
@app.get("/documents/", tags=["Document Management"])
async def list_documents(
    client = Depends(get_api_client),
    database: Session = Depends(get_db)
):
    """
    List all uploaded documents for the authenticated client.
    """
    documents = db.get_client_documents(database, client.id)
    
    return {
        "client_name": client.client_name,
        "total_documents": len(documents),
        "documents": [
            {
                "id": doc.id,
                "filename": doc.filename,
                "upload_date": doc.upload_date.isoformat(),
                "file_size": doc.file_size,
                "chunk_count": doc.chunk_count,
                "status": doc.status
            }
            for doc in documents
        ]
    }

@app.get("/documents/{document_id}", tags=["Document Management"])
async def get_document_details(
    document_id: int,
    client = Depends(get_api_client),
    database: Session = Depends(get_db)
):
    """
    Get details for a specific document.
    """
    doc = db.get_document_by_id(database, document_id, client.id)
    
    if not doc:
        raise HTTPException(status_code=404, detail="Document not found")
    
    return {
        "id": doc.id,
        "filename": doc.filename,
        "upload_date": doc.upload_date.isoformat(),
        "file_size": doc.file_size,
        "chunk_count": doc.chunk_count,
        "status": doc.status,
        "file_hash": doc.file_hash
    }

@app.delete("/documents/{document_id}", tags=["Document Management"])
async def delete_document(
    document_id: int,
    client = Depends(get_api_client),
    database: Session = Depends(get_db)
):
    """
    Delete a document from both the database and vector store.
    """
    from document_manager import delete_document_from_vectorstore
    
    # Get document to retrieve file_hash
    doc = db.get_document_by_id(database, document_id, client.id)
    
    if not doc:
        raise HTTPException(status_code=404, detail="Document not found")
    
    # Delete from vector store first
    vector_deleted = delete_document_from_vectorstore(client.id, doc.file_hash)
    
    # Delete metadata from database
    db_deleted = db.delete_document_metadata(database, document_id, client.id)
    
    if not db_deleted:
        raise HTTPException(status_code=500, detail="Failed to delete document metadata")
    
    return {
        "status": "success",
        "message": f"Document '{doc.filename}' deleted successfully",
        "vector_store_deleted": vector_deleted,
        "chunks_removed": doc.chunk_count
    }

# --- Root Endpoint ---
@app.get("/")
def read_root():
    return {"message": "Welcome to the Nutrition Chatbot API"}

# --- Main Entry Point ---
if __name__ == "__main__":
    port = int(os.environ.get("PORT", 8000))
    uvicorn.run(app, host="0.0.0.0", port=port)