[docs]asyncdefpublish_index(INDEX_DIR:Path,PUBLISHED_DIR:Path,index_name:str):"""Publish an index by creating a zip file containing index.json and persona directories."""try:index_dir=INDEX_DIR/index_nameifnotindex_dir.exists()ornotindex_dir.is_dir():raiseHTTPException(status_code=404,detail="Index directory not found")# Create a timestamp for the zip file nametimestamp=datetime.now().strftime('%Y%m%d_%H%M%S')zip_filename=f"{index_name}-{timestamp}.zip"zip_path=PUBLISHED_DIR/zip_filenamewithzipfile.ZipFile(zip_path,'w',zipfile.ZIP_DEFLATED)aszipf:# Add index.jsonindex_json_path=index_dir/'index.json'ifindex_json_path.exists():zipf.write(index_json_path,'index.json')# Add persona directories if they existpersonas_dir=index_dir/'personas'ifpersonas_dir.exists():forpersona_dirinpersonas_dir.iterdir():ifpersona_dir.is_dir():# Add all files from the persona directoryforroot,_,filesinos.walk(persona_dir):forfileinfiles:file_path=Path(root)/file# Create relative path for the zip filearc_name=f"personas/{persona_dir.name}/{file}"zipf.write(file_path,arc_name)# Return URL path that can be used with the static file handlerzip_url=f"/published/{zip_filename}"returnJSONResponse({'success':True,'message':'Index published successfully','zip_file':zip_url})exceptExceptionase:raiseHTTPException(status_code=500,detail=f"Failed to publish index: {str(e)}")
[docs]asyncdefinstall_index_from_zip(INDEX_DIR:Path,file:UploadFile):"""Install an index from a zip file."""ifnotfile.filename.endswith('.zip'):raiseHTTPException(status_code=400,detail="File must be a zip archive")# Create temporary directory for processingtemp_dir=Path("temp_index_install")temp_dir.mkdir(exist_ok=True)try:# Save uploaded filezip_path=temp_dir/file.filenamewithopen(zip_path,'wb')asf:shutil.copyfileobj(file.file,f)# Extract zip contentswithzipfile.ZipFile(zip_path,'r')aszip_ref:zip_ref.extractall(temp_dir)# Look for index.json in the extracted contentsindex_files=list(temp_dir.rglob('index.json'))ifnotindex_files:raiseHTTPException(status_code=400,detail="No index.json found in zip file")# Read the index metadatawithopen(index_files[0],'r')asf:index_data=json.load(f)index_name=index_data.get('name')ifnotindex_name:raiseHTTPException(status_code=400,detail="Invalid index.json: missing name field")# Process agents and their personasindex_root=index_files[0].parentpersonas_dir=index_root/'personas'ifpersonas_dir.exists():forpersona_dirinpersonas_dir.iterdir():ifpersona_dir.is_dir():persona_name=persona_dir.name# Install persona to the correct locationinstall_persona(persona_dir,persona_name)# Move index to final locationtarget_dir=INDEX_DIR/index_nameiftarget_dir.exists():shutil.rmtree(target_dir)# Create new index directory with index.jsontarget_dir.mkdir(parents=True)shutil.copy2(index_files[0],target_dir/'index.json')# Copy personas directory if it existsifpersonas_dir.exists():shutil.copytree(personas_dir,target_dir/'personas',dirs_exist_ok=True)returnJSONResponse({'success':True,'message':f"Index '{index_name}' installed successfully"})exceptExceptionase:raiseHTTPException(status_code=500,detail=f"Failed to install index: {str(e)}")finally:# Clean up temporary directoryiftemp_dir.exists():shutil.rmtree(temp_dir)