transcripts-api / app.py
shyameati's picture
Update app.py to serve index.html and improve API
da1806a
Raw
History Blame
3.19 kB
import json
import logging
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
import numpy as np
import os
app = FastAPI()
# ---------------------------------------------------------
# Logging
# ---------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s"
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------
# CORS (optional but useful for frontend)
# ---------------------------------------------------------
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------
# Lazy-loaded dataset
# ---------------------------------------------------------
DATASET_PATH = "transcripts.csv" # change if needed
df_cache = None
def load_dataset():
global df_cache
if df_cache is None:
logger.info("Loading dataset...")
if not os.path.exists(DATASET_PATH):
raise FileNotFoundError(f"Dataset not found: {DATASET_PATH}")
df_cache = pd.read_csv(DATASET_PATH)
logger.info(f"Dataset loaded with {len(df_cache)} rows.")
return df_cache
# ---------------------------------------------------------
# JSON-safe conversion
# ---------------------------------------------------------
def to_json_safe(obj):
if isinstance(obj, (np.integer, np.int64)):
return int(obj)
if isinstance(obj, (np.floating, np.float64)):
return float(obj)
if isinstance(obj, (np.ndarray, list)):
return [to_json_safe(x) for x in obj]
if isinstance(obj, dict):
return {k: to_json_safe(v) for k, v in obj.items()}
return obj
# ---------------------------------------------------------
# Serve index.html at "/"
# ---------------------------------------------------------
@app.get("/", response_class=HTMLResponse)
def serve_index():
if not os.path.exists("index.html"):
return "<h1>index.html not found</h1>"
with open("index.html", "r") as f:
return f.read()
# ---------------------------------------------------------
# List all tickers
# ---------------------------------------------------------
@app.get("/tickers")
def get_tickers():
df = load_dataset()
tickers = sorted(df["symbol"].unique().tolist())
return {"tickers": tickers}
# ---------------------------------------------------------
# Get transcript for a symbol
# ---------------------------------------------------------
@app.get("/transcript/{symbol}")
def get_transcript(symbol: str):
df = load_dataset()
symbol = symbol.upper()
logger.info(f"Fetching transcript for: {symbol}")
subset = df[df["symbol"] == symbol]
if subset.empty:
raise HTTPException(status_code=404, detail=f"No transcript found for {symbol}")
# Convert each row to JSON-safe dict
records = subset.to_dict(orient="records")
safe_records = [to_json_safe(r) for r in records]
return {"symbol": symbol, "records": safe_records}