utils.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. import requests
  6. import os
  7. import aiohttp
  8. import json
  9. from utils.misc import calculate_sha256
  10. from config import OLLAMA_API_BASE_URL
  11. router = APIRouter()
  12. class UploadBlobForm(BaseModel):
  13. filename: str
  14. from urllib.parse import urlparse
  15. def parse_huggingface_url(hf_url):
  16. try:
  17. # Parse the URL
  18. parsed_url = urlparse(hf_url)
  19. # Get the path and split it into components
  20. path_components = parsed_url.path.split("/")
  21. # Extract the desired output
  22. user_repo = "/".join(path_components[1:3])
  23. model_file = path_components[-1]
  24. return model_file
  25. except ValueError:
  26. return None
  27. async def download_file_stream(url, file_path, file_name, chunk_size=1024 * 1024):
  28. done = False
  29. if os.path.exists(file_path):
  30. current_size = os.path.getsize(file_path)
  31. else:
  32. current_size = 0
  33. headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}
  34. timeout = aiohttp.ClientTimeout(total=600) # Set the timeout
  35. async with aiohttp.ClientSession(timeout=timeout) as session:
  36. async with session.get(url, headers=headers) as response:
  37. total_size = int(response.headers.get("content-length", 0)) + current_size
  38. with open(file_path, "ab+") as file:
  39. async for data in response.content.iter_chunked(chunk_size):
  40. current_size += len(data)
  41. file.write(data)
  42. done = current_size == total_size
  43. progress = round((current_size / total_size) * 100, 2)
  44. yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n'
  45. if done:
  46. file.seek(0)
  47. hashed = calculate_sha256(file)
  48. file.seek(0)
  49. url = f"{OLLAMA_API_BASE_URL}/blobs/sha256:{hashed}"
  50. response = requests.post(url, data=file)
  51. if response.ok:
  52. res = {
  53. "done": done,
  54. "blob": f"sha256:{hashed}",
  55. "name": file_name,
  56. }
  57. os.remove(file_path)
  58. yield f"data: {json.dumps(res)}\n\n"
  59. else:
  60. raise "Ollama: Could not create blob, Please try again."
  61. @router.get("/download")
  62. async def download(
  63. url: str,
  64. ):
  65. # url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf"
  66. file_name = parse_huggingface_url(url)
  67. if file_name:
  68. os.makedirs("./uploads", exist_ok=True)
  69. file_path = os.path.join("./uploads", f"{file_name}")
  70. return StreamingResponse(
  71. download_file_stream(url, file_path, file_name),
  72. media_type="text/event-stream",
  73. )
  74. else:
  75. return None
  76. @router.post("/upload")
  77. async def upload(file: UploadFile = File(...)):
  78. os.makedirs("./uploads", exist_ok=True)
  79. file_path = os.path.join("./uploads", file.filename)
  80. async def file_write_stream():
  81. total = 0
  82. total_size = file.size
  83. chunk_size = 1024 * 1024
  84. done = False
  85. try:
  86. with open(file_path, "wb+") as f:
  87. while True:
  88. chunk = file.file.read(chunk_size)
  89. if not chunk:
  90. break
  91. f.write(chunk)
  92. total += len(chunk)
  93. done = total_size == total
  94. progress = round((total / total_size) * 100, 2)
  95. res = {
  96. "progress": progress,
  97. "total": total_size,
  98. "completed": total,
  99. }
  100. yield f"data: {json.dumps(res)}\n\n"
  101. if done:
  102. f.seek(0)
  103. hashed = calculate_sha256(f)
  104. f.seek(0)
  105. url = f"{OLLAMA_API_BASE_URL}/blobs/sha256:{hashed}"
  106. response = requests.post(url, data=f)
  107. if response.ok:
  108. res = {
  109. "done": done,
  110. "blob": f"sha256:{hashed}",
  111. "name": file.filename,
  112. }
  113. os.remove(file_path)
  114. yield f"data: {json.dumps(res)}\n\n"
  115. else:
  116. raise "Ollama: Could not create blob, Please try again."
  117. except Exception as e:
  118. res = {"error": str(e)}
  119. yield f"data: {json.dumps(res)}\n\n"
  120. return StreamingResponse(file_write_stream(), media_type="text/event-stream")