Spaces:
Running
Running
File size: 4,566 Bytes
e9cf1f6 665ea76 e9cf1f6 665ea76 c5037fe 818799a e9cf1f6 818799a e9cf1f6 818799a 7e692a2 e9cf1f6 7e692a2 82fdcfd 7e692a2 82fdcfd 7e692a2 e9cf1f6 82fdcfd e9cf1f6 82fdcfd e9cf1f6 7cd9df2 e9cf1f6 a66fdf2 e9cf1f6 665ea76 e9cf1f6 a66fdf2 e9cf1f6 665ea76 e9cf1f6 818799a e9cf1f6 c5037fe e9cf1f6 c5037fe e9cf1f6 818799a e9cf1f6 665ea76 e9cf1f6 | 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 | """FastAPI server for multi-accelerator startup search."""
import os
import sys
from contextlib import asynccontextmanager
from pathlib import Path
# Ensure project root is on sys.path when running as `python src/server.py`
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import subprocess
from fastapi import FastAPI, Query, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, Response
from src.search import SearchEngine
from src.render import render_company_page, company_path, SITE_URL
from src.embeddings import embeddings_filename, get_provider
engine: SearchEngine | None = None
def _embedding_files_to_fetch() -> list[str]:
"""Filenames to ensure locally (prefer multi-field for the active provider)."""
provider = get_provider()
return [embeddings_filename(provider, multi=True)]
@asynccontextmanager
async def lifespan(app: FastAPI):
global engine
from src.storage import ensure_embeddings, resolve_data_dir
# On Vercel, /var/task is read-only and azure .npy is gitignored — resolve a
# writable data dir and pull embeddings from HF Hub when missing.
data_dir = resolve_data_dir()
os.environ["DATA_DIR"] = str(data_dir)
ensure_embeddings(_embedding_files_to_fetch(), data_dir=data_dir)
import src.search as search_mod
search_mod.DATA_DIR = data_dir
engine = SearchEngine()
print(f"Loaded {len(engine.companies)} companies with embeddings of shape {engine.embeddings.shape}")
print(f"Embedding provider: {engine.embedder.provider}")
print(f"Data dir: {data_dir}")
yield
app = FastAPI(title="NicheFind — Startup Discovery Engine", lifespan=lifespan)
STATIC_DIR = Path(__file__).resolve().parent.parent / "static"
@app.get("/api/search")
def api_search(
q: str = Query(..., min_length=1, description="Search query — describe your problem or idea"),
min_score: float | None = Query(None, ge=0, le=1),
source: str | None = Query(None),
batch: str | None = Query(None),
industry: str | None = Query(None),
status: str | None = Query(None),
tag: str | None = Query(None),
):
score = min_score if min_score is not None else engine._default_min_score
results = engine.search(
q, min_score=score, source=source, batch=batch,
industry=industry, status=status, tag=tag,
)
return {"query": q, "reranker": engine.reranker, "count": len(results), "results": results}
@app.get("/api/filters")
def api_filters():
return engine.filters
@app.get("/api/company/{source}/{slug}")
def api_company(source: str, slug: str):
company = engine.get_company(source, slug)
if company is None:
raise HTTPException(status_code=404, detail="Company not found")
return {
"company": company,
"similar": engine.similar_companies(source, slug),
}
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
try:
_GIT_REV = subprocess.check_output(
["git", "rev-parse", "--short", "HEAD"], stderr=subprocess.DEVNULL
).decode().strip()
except Exception:
_GIT_REV = "1"
@app.get("/")
def index():
html = (STATIC_DIR / "index.html").read_text()
html = html.replace("/static/style.css", f"/static/style.css?v={_GIT_REV}")
html = html.replace("/static/app.js", f"/static/app.js?v={_GIT_REV}")
return HTMLResponse(html)
@app.get("/company/{source}/{slug}")
def company_page(source: str, slug: str):
company = engine.get_company(source, slug)
if company is None:
return HTMLResponse(
"<h1>Company not found</h1><p><a href='/'>Back to search</a></p>", status_code=404
)
similar = engine.similar_companies(source, slug)
return HTMLResponse(render_company_page(company, similar, git_rev=_GIT_REV))
@app.get("/robots.txt")
def robots():
return PlainTextResponse(f"User-agent: *\nAllow: /\nSitemap: {SITE_URL}/sitemap.xml\n")
@app.get("/sitemap.xml")
def sitemap():
urls = [f"{SITE_URL}/"] + [SITE_URL + company_path(c) for c in engine.companies]
body = "".join(f"<url><loc>{u}</loc></url>" for u in urls)
xml = (
'<?xml version="1.0" encoding="UTF-8"?>'
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
f"{body}</urlset>"
)
return Response(content=xml, media_type="application/xml")
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 8000))
uvicorn.run("src.server:app", host="0.0.0.0", port=port)
|