async def create_deep_fake_image(origin: UploadFile = File(...), target: UploadFile = File(...)): content_origin = await origin.read() ext = origin.filename[origin.filename.rfind('.'):] origin.filename = str(uuid.uuid4()).replace('-', '') + ext content_target = await target.read() ext = target.filename[target.filename.rfind('.'):] target.filename = str(uuid.uuid4()).replace('-', '') + ext origin_input = os.path.join(config.face_swap_img_path, origin.filename) target_input = os.path.join(config.face_swap_img_path, target.filename) output = os.path.join(config.face_swap_result_path, str(uuid.uuid4()).replace('-', '') + ".png") print("origin_input:", origin_input) print("target_input:", target_input) with open(origin_input, "wb") as fp: fp.write(content_origin) with open(target_input, "wb") as fp: fp.write(content_target) faceswap.makedeepface(upload_origin_image_path=origin_input, upload_target_image_path=target_input, output=output) return { "url": url.convert_path_to_url(output, base_url="/api/v1/content/") }
async def generate_font_from_sample_image(img_id: str, file: UploadFile = File(...)): # get image file.filename = f"{img_id}_sample.jpg" contents = await file.read() # <-- Important! pathlib.Path("buffer").mkdir(parents=True, exist_ok=True) path = pathlib.Path("buffer") / file.filename # example of how you can save the file with open(path, "wb") as f: f.write(contents) # read image as numpy array sample_chars = cv2.imread(path, 0) # gen font all_char_panel = font_generator.generate_font_from_sample_image(sample_chars) output_path = pathlib.Path("buffer") / f"{img_id}_font.jpg" cv2.imwrite(output_path, all_char_panel) # send to save in cloud storage if all_char_panel: # send as a form data (Top task) r = requests.post(f"dummy_url/image/result/{img_id}", files="xxxxx") if r.status_code == 200: return { "status": "success" } else: raise HTTPException(status_code=404, detail="Resource Not found")
async def create_dame_meme_video(image: UploadFile = File(...)): contents = await image.read() image.filename = image.filename.replace(' ', '') input_path = os.path.join(config.image_path, image.filename) output_path = os.path.join(config.video_path, str(uuid.uuid4()).replace('-', '') + ".mp4") with open(input_path, "wb") as fp: fp.write(contents) print("input:", input_path) dame.make_damedame(upload_image_path=input_path, output=output_path) return { "url": url.convert_path_to_url(output_path, base_url="/api/v1/content/") }
async def upload_file(file: UploadFile = File(...)): try: file.filename = "{}.jpg".format(time.strftime("%Y%m%d-%H%M%S")) image_destination = await save_upload_file(file) await publish(image_destination) except Exception as ex: return jsonable_encoder({ "image_name": file.filename, "error": "err", }) return jsonable_encoder({ "image_name": file.filename, "error": None, })
async def create_upload_files(background_tasks: BackgroundTasks, file: UploadFile = File(...)): """"Entrypoint for source separation.""" name = file.filename file.filename = str(random.getrandbits(32)) + '.mp3' if not os.path.exists('ready/'): os.makedirs('ready/') upload_folder = open(os.path.join('ready/', file.filename), 'wb+') shutil.copyfileobj(file.file, upload_folder) upload_folder.close() subprocess.call([ 'python3 -m demucs.separate {}/ready/{} --dl -n demucs_extra -d cpu'. format(os.getcwd(), file.filename) ], shell=True) with ZipFile('sources-{}.zip'.format(file.filename), 'w') as zip: zip.write( 'separated/demucs_extra/{}/bass.wav'.format( file.filename.replace('.mp3', '')), basename('separated/demucs_extra/{}/bass.wav'.format( file.filename.replace('.mp3', '')))) zip.write( 'separated/demucs_extra/{}/drums.wav'.format( file.filename.replace('.mp3', '')), basename('separated/demucs_extra/{}/drums.wav'.format( file.filename.replace('.mp3', '')))) zip.write( 'separated/demucs_extra/{}/other.wav'.format( file.filename.replace('.mp3', '')), basename('separated/demucs_extra/{}/other.wav'.format( file.filename.replace('.mp3', '')))) zip.write( 'separated/demucs_extra/{}/vocals.wav'.format( file.filename.replace('.mp3', '')), basename('separated/demucs_extra/{}/vocals.wav'.format( file.filename.replace('.mp3', '')))) background_tasks.add_task(cleanup, file.filename, name) return FileResponse('sources-{}.zip'.format(file.filename), media_type='application/zip', filename='sources-{}.zip'.format(name))
async def create_upload_file(request: Request, file: UploadFile = File(...)): if validate_mime_type(file.content_type): file_extension = file.content_type.split('/')[1] file.filename = f"{uuid.uuid4()}.{file_extension}" contents = await file.read() upload_file_to_s3(contents, file.filename, file_extension) return templates.TemplateResponse( "upload.html", { "request": request, "filename": file.filename, "message": "Image has been uploaded.", "status": "success" }) return templates.TemplateResponse( "upload.html", { "request": request, "message": "Invalid file format. Please try again.", "status": "fail" })
async def upload_file(created_by: int = Form(...), parent: int = Form(...), f: UploadFile = File(...), db: Session = Depends(utils.get_db)): db_folder = crud.get_folder_by_id(db, parent) # Check if the parent folder exists if not db_folder: raise HTTPException(status_code=404, detail="Folder not found") # Check that the user is actually the creator of the folder if db_folder.created_by != created_by: raise HTTPException(status_code=401, detail="Unauthorized to upload files to this folder") # response_files = [] # for f in files: # Check if file with same name exists in the parent folder. If yes, then append a string to rename the newly uploaded file existing_file = crud.get_file_by_name_in_parent(db, f.filename, parent) if existing_file: f.filename = "new_" + f.filename # Save the file to disk abs_path = os.path.join(db_folder.abs_path, f.filename) with open(abs_path, "wb") as buffer: shutil.copyfileobj(f.file, buffer) # Create an entry in the database as well new_file = schemas.FileCreate( name=f.filename, abs_path=abs_path, is_folder=False, parent=parent, created_by=created_by, created_on=date.today(), size=os.path.getsize(abs_path), file_type=os.path.splitext(abs_path)[1][1:] ) # response_files.append() return crud.create_file(db=db, f=new_file)