Spaces:
Running
Running
| import os | |
| import time | |
| import io | |
| import hashlib | |
| #2024-11-28 support bytes get_buffer_id,save_buffer | |
| def clear_old_files(dir="files",passed_time=60*60): | |
| try: | |
| files = os.listdir(dir) | |
| current_time = time.time() | |
| for file in files: | |
| file_path = os.path.join(dir,file) | |
| ctime = os.stat(file_path).st_ctime | |
| diff = current_time - ctime | |
| #print(f"ctime={ctime},current_time={current_time},passed_time={passed_time},diff={diff}") | |
| if diff > passed_time: | |
| os.remove(file_path) | |
| except: | |
| print("maybe still gallery using error") | |
| def get_buffer_id(buffer,length=32): | |
| if isinstance(buffer,bytes): | |
| value = buffer | |
| else: | |
| value=buffer.getvalue() | |
| hash_object = hashlib.sha256(value) | |
| hex_dig = hash_object.hexdigest() | |
| unique_id = hex_dig[:length] | |
| return unique_id | |
| def get_image_id(image): | |
| buffer = io.BytesIO() | |
| image.save(buffer, format='PNG') | |
| return get_buffer_id(buffer) | |
| def save_image(image,extension="jpg",dir_name="files"): | |
| id = get_image_id(image) | |
| os.makedirs(dir_name,exist_ok=True) | |
| file_path = f"{dir_name}/{id}.{extension}" | |
| image.save(file_path) | |
| return file_path | |
| def save_buffer(buffer,extension="webp",dir_name="files"): | |
| id = get_buffer_id(buffer) | |
| os.makedirs(dir_name,exist_ok=True) | |
| file_path = f"{dir_name}/{id}.{extension}" | |
| with open(file_path,"wb") as f: | |
| if isinstance(buffer,bytes): | |
| f.write(buffer) | |
| else: | |
| f.write(buffer.getvalue()) | |
| return file_path | |
| def write_file(file_path,text): | |
| with open(file_path, 'w', encoding='utf-8') as f: | |
| f.write(text) | |
| def read_file(file_path): | |
| """read the text of target file | |
| """ | |
| with open(file_path, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| return content |