utils.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from fastapi import APIRouter, UploadFile, File, BackgroundTasks
  2. from fastapi import Depends, HTTPException, status
  3. from starlette.responses import StreamingResponse
  4. from pydantic import BaseModel
  5. from utils.misc import calculate_sha256
  6. import requests
  7. import os
  8. import asyncio
  9. import json
  10. from config import OLLAMA_API_BASE_URL
  11. router = APIRouter()
  12. class UploadBlobForm(BaseModel):
  13. filename: str
  14. @router.post("/upload")
  15. async def upload(file: UploadFile = File(...)):
  16. os.makedirs("./uploads", exist_ok=True)
  17. file_path = os.path.join("./uploads", file.filename)
  18. def file_write_stream():
  19. total = 0
  20. total_size = file.size
  21. chunk_size = 1024 * 1024
  22. done = False
  23. try:
  24. with open(file_path, "wb") as f:
  25. while True:
  26. chunk = file.file.read(chunk_size)
  27. if not chunk:
  28. break
  29. f.write(chunk)
  30. total += len(chunk)
  31. done = total_size == total
  32. res = {
  33. "total": total_size,
  34. "uploaded": total,
  35. }
  36. yield f"data: {json.dumps(res)}\n\n"
  37. if done:
  38. with open(file_path, "rb") as f:
  39. hashed = calculate_sha256(f)
  40. f.seek(0)
  41. file_data = f.read()
  42. url = f"{OLLAMA_API_BASE_URL}/blobs/sha256:{hashed}"
  43. response = requests.post(url, data=file_data)
  44. if response.ok:
  45. res = {
  46. "done": done,
  47. "blob": f"sha256:{hashed}",
  48. }
  49. os.remove(file_path)
  50. yield f"data: {json.dumps(res)}\n\n"
  51. else:
  52. raise "Ollama: Could not create blob, Please try again."
  53. except Exception as e:
  54. res = {"error": str(e)}
  55. yield f"data: {json.dumps(res)}\n\n"
  56. return StreamingResponse(file_write_stream(), media_type="text/event-stream")