qualifier / backend /app /storage.py
Sethu0330's picture
Add FTL RFQ Qualifier agent + full SALES CRM app for HF Spaces testing
005df22 unverified
Raw History Blame Contribute Delete
2.64 kB
"""
Uploaded-CSV storage abstraction. Local disk (HF Spaces, current behavior) when
AZURE_STORAGE_CONNECTION_STRING isn't set; Azure Blob Storage when it is — needed on Azure
Functions/Static Web Apps, where a function instance's local disk isn't guaranteed to persist or
be shared across scaled-out instances the way a single long-lived container's disk is.
UploadedFile.file_path stores whichever form applies: a real filesystem path on local disk, or a
"blob://<name>" pseudo-path on Blob Storage — read_upload_csv() below dispatches on that prefix,
so callers don't need to know which backend is active.
"""
from __future__ import annotations
import io
import os
import uuid
from pathlib import Path
from typing import Optional
import pandas as pd
AZURE_STORAGE_CONNECTION_STRING = os.getenv("AZURE_STORAGE_CONNECTION_STRING", "").strip()
AZURE_STORAGE_CONTAINER = os.getenv("AZURE_STORAGE_CONTAINER", "uploads").strip() or "uploads"
USE_BLOB_STORAGE = bool(AZURE_STORAGE_CONNECTION_STRING)
_container_client = None
def _blob_container_client():
global _container_client
if _container_client is not None:
return _container_client
from azure.storage.blob import ContainerClient
client = ContainerClient.from_connection_string(
AZURE_STORAGE_CONNECTION_STRING, AZURE_STORAGE_CONTAINER
)
try:
client.create_container()
except Exception:
pass # already exists — fine, this just ensures it's there on first use
_container_client = client
return client
def save_upload_csv(content: bytes, *, file_id: Optional[str] = None) -> tuple[str, str]:
"""Persist an uploaded CSV's raw bytes. Returns (file_id, file_path) — file_path is what to
store in UploadedFile.file_path; pass it straight to read_upload_csv() later."""
fid = file_id or str(uuid.uuid4())
if USE_BLOB_STORAGE:
blob_name = f"{fid}.csv"
_blob_container_client().upload_blob(blob_name, content, overwrite=True)
return fid, f"blob://{blob_name}"
upload_dir = Path(os.getenv("HF_DATA_DIR", "/data")) / "uploads"
upload_dir.mkdir(parents=True, exist_ok=True)
path = upload_dir / f"{fid}.csv"
path.write_bytes(content)
return fid, str(path)
def read_upload_csv(file_path: str) -> pd.DataFrame:
"""Read a CSV previously saved via save_upload_csv(), regardless of which backend saved it."""
if file_path.startswith("blob://"):
blob_name = file_path[len("blob://"):]
data = _blob_container_client().download_blob(blob_name).readall()
return pd.read_csv(io.BytesIO(data))
return pd.read_csv(file_path)