1+ import os
2+ import tempfile
3+ import json
4+ import requests
5+ import pandas as pd
6+ from fastapi import APIRouter , HTTPException , Query
7+ from dotenv import load_dotenv
8+
9+ # Load .env file (make sure you have HF_TOKEN inside it)
10+ load_dotenv ()
11+
12+ router = APIRouter ()
13+
14+ HF_REPO_ID = os .getenv ("HF_DATA_REPO" ) # your repo ID
15+ HF_TOKEN = os .getenv ("HF_TOKEN" ) # Hugging Face API token
16+ BASE_URL = f"https://huggingface.co/datasets/{ HF_REPO_ID } /resolve/main/uploads"
17+
18+
19+ @router .get ("/get-file" )
20+ async def get_file (filename : str = Query (..., description = "Filename to extract from Hugging Face dataset" )):
21+ try :
22+ file_url = f"{ BASE_URL } /{ filename } .csv"
23+
24+ headers = {}
25+ if HF_TOKEN :
26+ headers ["Authorization" ] = f"Bearer { HF_TOKEN } "
27+
28+ response = requests .get (file_url , headers = headers )
29+
30+ if response .status_code != 200 :
31+ raise HTTPException (status_code = 404 , detail = f"File not found at { file_url } " )
32+
33+ # Save temporarily
34+ with tempfile .NamedTemporaryFile (delete = False , suffix = ".csv" ) as tmp :
35+ tmp .write (response .content )
36+ tmp_path = tmp .name
37+
38+ # Load with pandas
39+ df = pd .read_csv (tmp_path )
40+
41+ # Clean data for JSON
42+ df = df .replace ([float ("inf" ), float ("-inf" )], None )
43+ df = df .where (pd .notnull (df ), None )
44+
45+ json_str = df .head (50 ).to_json (orient = "records" , force_ascii = False , default_handler = str )
46+ records = json .loads (json_str )
47+
48+ return {"filename" : filename , "records" : records }
49+
50+ except Exception as e :
51+ raise HTTPException (status_code = 500 , detail = f"Error processing file: { str (e )} " )
0 commit comments