Spaces:
Runtime error
Runtime error
deploy: update
Browse files- .env.example +3 -6
- backend/app/api/routes/auth.py +1 -1
- backend/config_local.py +20 -0
- backend/core/config.py +26 -19
- backend/core/logging.py +2 -1
- backend/database.py +5 -14
- backend/main.py +20 -14
- frontend-react/.gitignore +1 -0
- package.json +2 -1
- start.ps1 +1 -1
.env.example
CHANGED
|
@@ -18,14 +18,11 @@ VITE_BACKEND_URL=http://localhost:8001
|
|
| 18 |
VITE_API_URL=http://localhost:8001
|
| 19 |
|
| 20 |
# Auth (Item 3) β set a strong password and secret before deploying
|
| 21 |
-
AUTH_USERNAME=
|
| 22 |
-
AUTH_PASSWORD=
|
| 23 |
JWT_SECRET=change-this-secret-in-production
|
| 24 |
JWT_EXPIRE_HOURS=24
|
| 25 |
|
| 26 |
# Credential encryption (Item 5)
|
| 27 |
# Generate with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
|
| 28 |
-
ENCRYPTION_KEY=
|
| 29 |
-
|
| 30 |
-
AUTH_USERNAME=root
|
| 31 |
-
AUTH_PASSWORD=root
|
|
|
|
| 18 |
VITE_API_URL=http://localhost:8001
|
| 19 |
|
| 20 |
# Auth (Item 3) β set a strong password and secret before deploying
|
| 21 |
+
AUTH_USERNAME=your_username_here
|
| 22 |
+
AUTH_PASSWORD=your_password_here
|
| 23 |
JWT_SECRET=change-this-secret-in-production
|
| 24 |
JWT_EXPIRE_HOURS=24
|
| 25 |
|
| 26 |
# Credential encryption (Item 5)
|
| 27 |
# Generate with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
|
| 28 |
+
ENCRYPTION_KEY=
|
|
|
|
|
|
|
|
|
backend/app/api/routes/auth.py
CHANGED
|
@@ -14,7 +14,7 @@ class LoginRequest(BaseModel):
|
|
| 14 |
|
| 15 |
@router.post("/login")
|
| 16 |
def login(body: LoginRequest):
|
| 17 |
-
if body.username != settings.AUTH_USERNAME or body.password != settings.AUTH_PASSWORD:
|
| 18 |
raise HTTPException(status_code=401, detail="Invalid credentials")
|
| 19 |
token = create_access_token(body.username)
|
| 20 |
return {"access_token": token, "token_type": "bearer"}
|
|
|
|
| 14 |
|
| 15 |
@router.post("/login")
|
| 16 |
def login(body: LoginRequest):
|
| 17 |
+
if body.username.lower() != settings.AUTH_USERNAME.lower() or body.password != settings.AUTH_PASSWORD:
|
| 18 |
raise HTTPException(status_code=401, detail="Invalid credentials")
|
| 19 |
token = create_access_token(body.username)
|
| 20 |
return {"access_token": token, "token_type": "bearer"}
|
backend/config_local.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MISTRAL_API_KEY = "BLPcRhKaWFpTb0JkvwLdwKejwTUmFo1d"
|
| 2 |
+
|
| 3 |
+
LLM_MODEL = "mistral-large-latest"
|
| 4 |
+
LLM_FALLBACK_MODEL = "open-mistral-7b"
|
| 5 |
+
MAX_TOKENS_PER_SESSION = 0
|
| 6 |
+
|
| 7 |
+
DATABASE_URL = "postgresql://postgres:FPgZeZ0aT3ENxyav@db.akrvdknpkzedwpadglfu.supabase.co:5432/postgres"
|
| 8 |
+
SUPABASE_URL = "https://akrvdknpkzedwpadglfu.supabase.co"
|
| 9 |
+
SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImFrcnZka25wa3plZHdwYWRnbGZ1Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzM4MTUwNDEsImV4cCI6MjA4OTM5MTA0MX0.t_0NtRBBg3cY6umSgB_GXWk_8Cy8qJ-XPt3CWQ--wCo"
|
| 10 |
+
SUPABASE_STORAGE_BUCKET = "assets"
|
| 11 |
+
SUPABASE_SERVICE_ROLE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImFrcnZka25wa3plZHdwYWRnbGZ1Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3MzgxNTA0MSwiZXhwIjoyMDg5MzkxMDQxfQ.c9PrYaixqiSx_NFQQ7Lfb6Bf_R1o3estYY03HY2SZA4"
|
| 12 |
+
|
| 13 |
+
ALLOWED_ORIGINS = "http://localhost:5173,http://localhost:5174,http://localhost:3000"
|
| 14 |
+
|
| 15 |
+
AUTH_USERNAME = "Amitkasar"
|
| 16 |
+
AUTH_PASSWORD = "Amit@testing"
|
| 17 |
+
JWT_SECRET = "9d02ade8f0c326ff2c0f84bd3e8fa982ee9560b27b6c4d196e094dc1a051dea9"
|
| 18 |
+
JWT_EXPIRE_HOURS = 24
|
| 19 |
+
|
| 20 |
+
ENCRYPTION_KEY = "37RRawx1OWpnWnulBiNrsdIrGyWV42YNa9N_4vLMrFk="
|
backend/core/config.py
CHANGED
|
@@ -1,32 +1,39 @@
|
|
| 1 |
-
|
| 2 |
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
UPLOAD_DIR: str = "backend/uploads"
|
| 9 |
LLM_TIMEOUT: int = 60
|
| 10 |
HTTP_TIMEOUT: int = 120
|
| 11 |
RESPONSE_TRUNCATION_LIMIT: int = 4000
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
LLM_FALLBACK_MODEL: str = "open-mistral-7b"
|
| 16 |
-
|
| 17 |
-
# Token budget cap per session β 0 = no limit (Item 17)
|
| 18 |
-
MAX_TOKENS_PER_SESSION: int = 0
|
| 19 |
|
| 20 |
-
|
| 21 |
-
AUTH_USERNAME: str = "admin"
|
| 22 |
-
AUTH_PASSWORD: str = "changeme"
|
| 23 |
-
JWT_SECRET: str = "change-this-secret-in-production"
|
| 24 |
-
JWT_EXPIRE_HOURS: int = 24
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
|
| 31 |
@property
|
| 32 |
def allowed_origins_list(self) -> list[str]:
|
|
|
|
| 1 |
+
import os
|
| 2 |
|
| 3 |
+
from backend import config_local as _local
|
| 4 |
|
| 5 |
+
|
| 6 |
+
def _cfg(key: str, default):
|
| 7 |
+
# Priority: environment variable > config_local.py > hardcoded default
|
| 8 |
+
if key in os.environ:
|
| 9 |
+
raw = os.environ[key]
|
| 10 |
+
# Coerce to the same type as the default (e.g. int for JWT_EXPIRE_HOURS)
|
| 11 |
+
if isinstance(default, int):
|
| 12 |
+
return int(raw)
|
| 13 |
+
return raw
|
| 14 |
+
return getattr(_local, key, default)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Settings:
|
| 18 |
+
MISTRAL_API_KEY: str = _cfg("MISTRAL_API_KEY", "")
|
| 19 |
+
DATABASE_URL: str = _cfg("DATABASE_URL", "")
|
| 20 |
+
ALLOWED_ORIGINS: str = _cfg("ALLOWED_ORIGINS", "http://localhost:5173,http://localhost:3000")
|
| 21 |
UPLOAD_DIR: str = "backend/uploads"
|
| 22 |
LLM_TIMEOUT: int = 60
|
| 23 |
HTTP_TIMEOUT: int = 120
|
| 24 |
RESPONSE_TRUNCATION_LIMIT: int = 4000
|
| 25 |
|
| 26 |
+
LLM_MODEL: str = _cfg("LLM_MODEL", "mistral-large-latest")
|
| 27 |
+
LLM_FALLBACK_MODEL: str = _cfg("LLM_FALLBACK_MODEL", "open-mistral-7b")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
MAX_TOKENS_PER_SESSION: int = _cfg("MAX_TOKENS_PER_SESSION", 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
AUTH_USERNAME: str = _cfg("AUTH_USERNAME", "admin")
|
| 32 |
+
AUTH_PASSWORD: str = _cfg("AUTH_PASSWORD", "changeme")
|
| 33 |
+
JWT_SECRET: str = _cfg("JWT_SECRET", "change-this-secret-in-production")
|
| 34 |
+
JWT_EXPIRE_HOURS: int = _cfg("JWT_EXPIRE_HOURS", 24)
|
| 35 |
|
| 36 |
+
ENCRYPTION_KEY: str = _cfg("ENCRYPTION_KEY", "")
|
| 37 |
|
| 38 |
@property
|
| 39 |
def allowed_origins_list(self) -> list[str]:
|
backend/core/logging.py
CHANGED
|
@@ -8,8 +8,9 @@ def get_logger(name: str) -> logging.Logger:
|
|
| 8 |
handler = logging.StreamHandler(sys.stdout)
|
| 9 |
handler.setFormatter(logging.Formatter(
|
| 10 |
"%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 11 |
-
datefmt="%
|
| 12 |
))
|
| 13 |
logger.addHandler(handler)
|
| 14 |
logger.setLevel(logging.INFO)
|
|
|
|
| 15 |
return logger
|
|
|
|
| 8 |
handler = logging.StreamHandler(sys.stdout)
|
| 9 |
handler.setFormatter(logging.Formatter(
|
| 10 |
"%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 11 |
+
datefmt="%H:%M:%S",
|
| 12 |
))
|
| 13 |
logger.addHandler(handler)
|
| 14 |
logger.setLevel(logging.INFO)
|
| 15 |
+
logger.propagate = False # don't bubble up to root; use our handler only
|
| 16 |
return logger
|
backend/database.py
CHANGED
|
@@ -1,30 +1,21 @@
|
|
| 1 |
import logging
|
| 2 |
-
import os
|
| 3 |
import uuid
|
| 4 |
from datetime import datetime, timezone
|
| 5 |
|
| 6 |
|
| 7 |
def _utcnow():
|
| 8 |
return datetime.now(timezone.utc)
|
| 9 |
-
from pathlib import Path
|
| 10 |
|
| 11 |
-
from
|
| 12 |
-
from sqlalchemy import Boolean, Column, DateTime, Float, ForeignKey, Integer, JSON, String, Table, Text, Unicode, create_engine
|
| 13 |
from sqlalchemy.orm import declarative_base, relationship, sessionmaker
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
# Load environment variables from .env file (handling both root and subfolder execution)
|
| 18 |
-
env_path = Path(__file__).resolve().parent.parent / '.env'
|
| 19 |
-
if not env_path.exists():
|
| 20 |
-
# Fallback to current directory for edge cases
|
| 21 |
-
env_path = Path('.env').resolve()
|
| 22 |
|
| 23 |
-
|
| 24 |
|
| 25 |
-
DATABASE_URL =
|
| 26 |
if not DATABASE_URL:
|
| 27 |
-
raise ValueError(
|
| 28 |
|
| 29 |
# Fix for common PostgreSQL connection string prefixes
|
| 30 |
if DATABASE_URL.startswith("postgres://"):
|
|
|
|
| 1 |
import logging
|
|
|
|
| 2 |
import uuid
|
| 3 |
from datetime import datetime, timezone
|
| 4 |
|
| 5 |
|
| 6 |
def _utcnow():
|
| 7 |
return datetime.now(timezone.utc)
|
|
|
|
| 8 |
|
| 9 |
+
from sqlalchemy import Boolean, Column, DateTime, Float, ForeignKey, Integer, JSON, String, Table, Text, create_engine
|
|
|
|
| 10 |
from sqlalchemy.orm import declarative_base, relationship, sessionmaker
|
| 11 |
|
| 12 |
+
from backend.core.config import settings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
|
| 16 |
+
DATABASE_URL = settings.DATABASE_URL
|
| 17 |
if not DATABASE_URL:
|
| 18 |
+
raise ValueError("DATABASE_URL is not set. Add it to backend/config_local.py")
|
| 19 |
|
| 20 |
# Fix for common PostgreSQL connection string prefixes
|
| 21 |
if DATABASE_URL.startswith("postgres://"):
|
backend/main.py
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
|
|
| 1 |
import os
|
| 2 |
import time
|
| 3 |
from pathlib import Path
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import jwt as _pyjwt
|
| 6 |
-
from alembic import command as alembic_command
|
| 7 |
-
from alembic.config import Config as AlembicConfig
|
| 8 |
from cryptography.fernet import Fernet
|
| 9 |
from fastapi import Depends, FastAPI, Request
|
| 10 |
from fastapi.exceptions import RequestValidationError
|
|
@@ -25,13 +33,6 @@ import backend.app.api.routes.settings as llm_settings_router
|
|
| 25 |
|
| 26 |
logger = get_logger(__name__)
|
| 27 |
|
| 28 |
-
# Run any pending Alembic migrations before the app starts accepting requests
|
| 29 |
-
try:
|
| 30 |
-
_alembic_cfg = AlembicConfig(str(Path(__file__).resolve().parent.parent / "alembic.ini"))
|
| 31 |
-
alembic_command.upgrade(_alembic_cfg, "head")
|
| 32 |
-
except Exception as _e:
|
| 33 |
-
logger.warning("Alembic auto-upgrade skipped: %s. Run 'alembic upgrade head' manually.", _e)
|
| 34 |
-
|
| 35 |
# Validate ENCRYPTION_KEY at startup β fail fast rather than silently storing plaintext
|
| 36 |
if not settings.ENCRYPTION_KEY:
|
| 37 |
raise RuntimeError(
|
|
@@ -57,12 +58,17 @@ app.state.limiter = limiter
|
|
| 57 |
@app.middleware("http")
|
| 58 |
async def request_logger(request: Request, call_next):
|
| 59 |
start = time.perf_counter()
|
| 60 |
-
response = await call_next(request)
|
| 61 |
-
ms = (time.perf_counter() - start) * 1000
|
| 62 |
-
status = response.status_code
|
| 63 |
qs = f"?{request.url.query}" if request.url.query else ""
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
|
| 68 |
@app.middleware("http")
|
|
|
|
| 1 |
+
import logging
|
| 2 |
import os
|
| 3 |
import time
|
| 4 |
from pathlib import Path
|
| 5 |
|
| 6 |
+
# Force logging config AFTER uvicorn sets up its own β this runs at import time
|
| 7 |
+
# which is after uvicorn's dictConfig, so it takes precedence.
|
| 8 |
+
logging.basicConfig(
|
| 9 |
+
level=logging.INFO,
|
| 10 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 11 |
+
datefmt="%H:%M:%S",
|
| 12 |
+
force=True, # overrides any existing root-logger handlers
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
import jwt as _pyjwt
|
|
|
|
|
|
|
| 16 |
from cryptography.fernet import Fernet
|
| 17 |
from fastapi import Depends, FastAPI, Request
|
| 18 |
from fastapi.exceptions import RequestValidationError
|
|
|
|
| 33 |
|
| 34 |
logger = get_logger(__name__)
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
# Validate ENCRYPTION_KEY at startup β fail fast rather than silently storing plaintext
|
| 37 |
if not settings.ENCRYPTION_KEY:
|
| 38 |
raise RuntimeError(
|
|
|
|
| 58 |
@app.middleware("http")
|
| 59 |
async def request_logger(request: Request, call_next):
|
| 60 |
start = time.perf_counter()
|
|
|
|
|
|
|
|
|
|
| 61 |
qs = f"?{request.url.query}" if request.url.query else ""
|
| 62 |
+
logger.info("β %s %s%s", request.method, request.url.path, qs)
|
| 63 |
+
try:
|
| 64 |
+
response = await call_next(request)
|
| 65 |
+
ms = (time.perf_counter() - start) * 1000
|
| 66 |
+
logger.info("β %s %s%s %d (%.0fms)", request.method, request.url.path, qs, response.status_code, ms)
|
| 67 |
+
return response
|
| 68 |
+
except Exception as exc:
|
| 69 |
+
ms = (time.perf_counter() - start) * 1000
|
| 70 |
+
logger.error("β %s %s%s ERROR (%.0fms): %s", request.method, request.url.path, qs, ms, exc)
|
| 71 |
+
raise
|
| 72 |
|
| 73 |
|
| 74 |
@app.middleware("http")
|
frontend-react/.gitignore
CHANGED
|
@@ -22,3 +22,4 @@ dist-ssr
|
|
| 22 |
*.njsproj
|
| 23 |
*.sln
|
| 24 |
*.sw?
|
|
|
|
|
|
| 22 |
*.njsproj
|
| 23 |
*.sln
|
| 24 |
*.sw?
|
| 25 |
+
.vercel
|
package.json
CHANGED
|
@@ -10,7 +10,8 @@
|
|
| 10 |
"setup:frontend": "npm install --prefix frontend-react",
|
| 11 |
"setup:backend": "pip install -r requirements.txt",
|
| 12 |
"setup": "npm run setup:backend && npm run setup:frontend",
|
| 13 |
-
"build": "npm run build --prefix frontend-react"
|
|
|
|
| 14 |
},
|
| 15 |
"devDependencies": {
|
| 16 |
"concurrently": "^8.2.2"
|
|
|
|
| 10 |
"setup:frontend": "npm install --prefix frontend-react",
|
| 11 |
"setup:backend": "pip install -r requirements.txt",
|
| 12 |
"setup": "npm run setup:backend && npm run setup:frontend",
|
| 13 |
+
"build": "npm run build --prefix frontend-react",
|
| 14 |
+
"deploy": "git add . && git commit -m \"deploy: update\" && git push origin main && git push hf main"
|
| 15 |
},
|
| 16 |
"devDependencies": {
|
| 17 |
"concurrently": "^8.2.2"
|
start.ps1
CHANGED
|
@@ -26,7 +26,7 @@ if ($stale) {
|
|
| 26 |
# --- 2. Start FastAPI Backend ---
|
| 27 |
Write-Host "[2/3] Starting FastAPI backend (port 8001)..." -ForegroundColor Yellow
|
| 28 |
$backend = Start-Process -FilePath "cmd.exe" `
|
| 29 |
-
-ArgumentList "/k", "title Backend && python -m uvicorn backend.main:app --reload --port 8001" `
|
| 30 |
-WorkingDirectory $PSScriptRoot `
|
| 31 |
-PassThru
|
| 32 |
|
|
|
|
| 26 |
# --- 2. Start FastAPI Backend ---
|
| 27 |
Write-Host "[2/3] Starting FastAPI backend (port 8001)..." -ForegroundColor Yellow
|
| 28 |
$backend = Start-Process -FilePath "cmd.exe" `
|
| 29 |
+
-ArgumentList "/k", "title Backend && python -m uvicorn backend.main:app --reload --port 8001 --log-level info" `
|
| 30 |
-WorkingDirectory $PSScriptRoot `
|
| 31 |
-PassThru
|
| 32 |
|