Spaces:
Runtime error
Runtime error
from peewee import BlobField, CharField, IntegrityError, Model, SqliteDatabase | |
import datetime | |
import os.path | |
import pickle | |
import tempfile | |
################################################################################ | |
class Gallery(Model): | |
id = CharField(primary_key=True) | |
path = CharField(unique=True) | |
metadata = BlobField() | |
class Meta: | |
database = SqliteDatabase(f'{tempfile.gettempdir()}/.db') | |
Gallery.create_table() | |
################################################################################ | |
def delete(path): | |
Gallery.delete().where(Gallery.path == path).execute() | |
def delete_by_id(id): | |
Gallery.delete().where(Gallery.id == id).execute() | |
def exists(path): | |
return Gallery.select().where(Gallery.path == path).exists() | |
def exists_by_id(id): | |
return Gallery.select().where(Gallery.id == id).exists() | |
def get(path): | |
image = Gallery.get(Gallery.path == path) | |
return image.id, pickle.loads(image.metadata) | |
def get_by_id(id): | |
image = Gallery.get(Gallery.id == id) | |
return image.path, pickle.loads(image.metadata) | |
def tuples(): | |
images = [] | |
for id, path, metadata in Gallery.select().order_by(Gallery.id).tuples(): | |
images.append((id, path, pickle.loads(metadata))) | |
return images | |
def update(path, metadata): | |
metadata = pickle.dumps(metadata) | |
if os.path.basename(path) == 'webcam.png': | |
timestamp = datetime.datetime.fromtimestamp( | |
os.path.getctime(path)).strftime('%Y%m%d_%H%M%S') | |
id = f'DCIM/Camera/{timestamp}.png' | |
else: | |
id = f'DCIM/Upload/{os.path.basename(path)}' | |
try: | |
Gallery.create(id=id, path=path, metadata=metadata) | |
except IntegrityError: | |
Gallery.set_by_id(id, dict(path=path, metadata=metadata)) | |
return id | |