Spaces:
Sleeping
Sleeping
Download main.py from rizzdeep/phi3-ds-expert: direct link, hf CLI and curl.
- Browser
- Download file 4.93 kB
-
https://huggingface.co/spaces/rizzdeep/phi3-ds-expert/resolve/main/main.py
- Command line
-
hf download hf://spaces/rizzdeep/phi3-ds-expert/main.py
-
curl -L -o main.py https://huggingface.co/spaces/rizzdeep/phi3-ds-expert/resolve/main/main.py
4.93 kB
| from fastapi import FastAPI, File, UploadFile, HTTPException, Request, BackgroundTasks | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| import pandas as pd | |
| import io | |
| import torch | |
| from peft import PeftModel, PeftConfig | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| import uvicorn | |
| import nest_asyncio | |
| import os | |
| import uuid | |
| # Allow uvicorn to run inside Colab / Spaces | |
| nest_asyncio.apply() | |
| # ========== Environment Setup ========== | |
| device = "cpu" | |
| offload_dir = "/data/model_offload" | |
| os.makedirs(offload_dir, exist_ok=True) | |
| adapter_path = "./phi3-ds-expert-lora" | |
| base_model_id = "microsoft/Phi-3-mini-4k-instruct" | |
| peft_config = PeftConfig.from_pretrained(adapter_path) | |
| base_model = AutoModelForCausalLM.from_pretrained( | |
| base_model_id, | |
| torch_dtype="auto", | |
| device_map={"": "cpu"}, | |
| offload_folder=offload_dir | |
| ) | |
| tokenizer = AutoTokenizer.from_pretrained(base_model_id) | |
| tokenizer.pad_token = tokenizer.eos_token | |
| model = PeftModel.from_pretrained( | |
| base_model, | |
| adapter_path, | |
| offload_folder=offload_dir | |
| ) | |
| model.to(device) | |
| model.eval() | |
| # ========== FastAPI App ========== | |
| app = FastAPI() | |
| # CORS middleware config | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Global dataset storage | |
| uploaded_df = None | |
| # In-memory job results store | |
| job_results = {} | |
| # ========== Pydantic Request Schema ========== | |
| class PromptRequest(BaseModel): | |
| prompt: str | |
| # ========== Prompt Generation Helper ========== | |
| def generate_prompt(prompt_text, df=None): | |
| context = "" | |
| if df is not None: | |
| context += f"Dataset Columns: {list(df.columns)}\n" | |
| context += f"Shape: {df.shape}\n" | |
| context += f"First 1 row:\n{df.head(1).to_string(index=False)}\n" | |
| final_prompt = ( | |
| f"You are a data science expert. Use the dataset context below to help the user.\n\n" | |
| f"{context}\n\nUser Question: {prompt_text}\nAssistant:" | |
| ) | |
| inputs = tokenizer(final_prompt, return_tensors="pt", truncation=True, max_length=2048).to(device) | |
| input_length = inputs.input_ids.shape[1] | |
| with torch.no_grad(): | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=128, | |
| do_sample=False, | |
| eos_token_id=tokenizer.eos_token_id, | |
| pad_token_id=tokenizer.eos_token_id | |
| ) | |
| generated_tokens = outputs[0][input_length:] | |
| response = tokenizer.decode(generated_tokens, skip_special_tokens=True).strip() | |
| return response | |
| # ========== Background Inference Task ========== | |
| def run_inference(prompt_text, job_id, df=None): | |
| result = generate_prompt(prompt_text, df) | |
| job_results[job_id] = result | |
| # ========== API Endpoints ========== | |
| def read_root(): | |
| return {"message": "🚀 API is live and running!"} | |
| async def generate(request: PromptRequest, background_tasks: BackgroundTasks): | |
| if not request.prompt.strip(): | |
| raise HTTPException(status_code=400, detail="Prompt cannot be empty.") | |
| job_id = str(uuid.uuid4()) | |
| job_results[job_id] = "processing" | |
| background_tasks.add_task(run_inference, request.prompt, job_id, uploaded_df) | |
| return {"job_id": job_id} | |
| async def job_status(job_id: str): | |
| if job_id not in job_results: | |
| raise HTTPException(status_code=404, detail="Job ID not found") | |
| result = job_results[job_id] | |
| if result == "processing": | |
| return {"status": "processing"} | |
| else: | |
| return {"status": "complete", "result": result} | |
| MAX_FILE_SIZE = 15 * 1024 * 1024 # 15 MB | |
| async def upload_file(request: Request, file: UploadFile = File(...)): | |
| global uploaded_df | |
| content_length = request.headers.get("content-length") | |
| if content_length and int(content_length) > MAX_FILE_SIZE: | |
| raise HTTPException(status_code=413, detail="File too large. Max size is 15 MB.") | |
| content = await file.read() | |
| if len(content) > MAX_FILE_SIZE: | |
| raise HTTPException(status_code=413, detail="File too large. Max size is 15 MB.") | |
| try: | |
| if file.filename.endswith(".csv"): | |
| uploaded_df = pd.read_csv(io.BytesIO(content)) | |
| elif file.filename.endswith((".xls", ".xlsx")): | |
| uploaded_df = pd.read_excel(io.BytesIO(content)) | |
| else: | |
| raise HTTPException(status_code=400, detail="Only CSV and Excel files are supported.") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Error while uploading file: {str(e)}") | |
| async def health_check(): | |
| return { | |
| "status": "healthy", | |
| "device": device, | |
| "model_loaded": model is not None, | |
| "dataset_uploaded": uploaded_df is not None | |
| } | |
| # Run the FastAPI app | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |