Spaces:
Sleeping
Sleeping
| import os,shutil,base64 | |
| PROJECTS_ROOT='projects' | |
| def ensure_project(name): | |
| p=os.path.join(PROJECTS_ROOT,name); os.makedirs(p,exist_ok=True); return p | |
| def list_project(name): | |
| p=ensure_project(name); files=[] | |
| for root,dirs,filenames in os.walk(p): | |
| for fn in filenames: | |
| files.append(os.path.relpath(os.path.join(root,fn),p)) | |
| return files | |
| def read_file(project,relpath): | |
| p=ensure_project(project); full=os.path.join(p,relpath) | |
| if not os.path.exists(full): return 'Error: not found' | |
| try: | |
| return open(full,'r',encoding='utf-8',errors='ignore').read() | |
| except: | |
| return base64.b64encode(open(full,'rb').read()).decode('utf-8') | |
| def save_file(project,relpath,content): | |
| p=ensure_project(project); full=os.path.join(p,relpath); d=os.path.dirname(full) | |
| if d: os.makedirs(os.path.join(p,d),exist_ok=True) | |
| open(full,'w',encoding='utf-8').write(content); return full | |
| def delete_path(project,relpath): | |
| p=ensure_project(project); full=os.path.join(p,relpath) | |
| if os.path.isdir(full): shutil.rmtree(full); return True | |
| if os.path.exists(full): os.remove(full); return True; return False | |
| def make_folder(project,relpath): | |
| p=ensure_project(project); full=os.path.join(p,relpath); os.makedirs(full,exist_ok=True); return full | |
| def save_uploaded_file(project,file_like): | |
| try: | |
| if hasattr(file_like,'name'): | |
| src=file_like.name; dest=os.path.join(ensure_project(project), os.path.basename(src)); shutil.copy(src,dest); return {'path':dest,'relpath':os.path.basename(dest)} | |
| if isinstance(file_like,str) and os.path.exists(file_like): | |
| dest=os.path.join(ensure_project(project), os.path.basename(file_like)); shutil.copy(file_like,dest); return {'path':dest,'relpath':os.path.basename(dest)} | |
| except Exception as e: | |
| return {'error':str(e)} | |
| return {'error':'could not save uploaded file'} | |