File size: 1,322 Bytes
3f6f2e9 7ef144b 3f6f2e9 7ef144b 3f6f2e9 ae11f2d dae7f12 3f6f2e9 f76c26d dae7f12 3f6f2e9 f76c26d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import os
import uuid
import requests
from typing import Tuple
import shelve
import tempfile
class DocumentManager:
def __init__(self, document_url: str):
self.document_url = document_url
self.DIR = os.path.join(tempfile.gettempdir(), "doc_cache")
os.makedirs(self.DIR, exist_ok=True)
cached_path = self._get_cached_path()
if cached_path and os.path.exists(cached_path):
print("Document already cached.")
self.file_path = cached_path
else:
self.file_path, _ = self._download_and_cache()
print("Document not cached.")
def _get_cached_path(self) -> str:
with shelve.open(os.path.join(self.DIR, 'cache')) as cache:
return cache.get(self.document_url, '')
def _download_and_cache(self) -> Tuple[str, str]:
response = requests.get(self.document_url, timeout=60)
response.raise_for_status()
filename = f"{uuid.uuid4()}.pdf"
file_path = os.path.join(self.DIR, filename)
with open(file_path, "wb") as f:
f.write(response.content)
with shelve.open(os.path.join(self.DIR, 'cache')) as cache:
cache[self.document_url] = file_path
return file_path, filename
def get_filepath(self) -> str:
return self.file_path |