Spaces:
Runtime error
Runtime error
selfitcamera commited on
Commit ·
9aefdc2
1
Parent(s): c276a99
init
Browse files11 unmodified lines12131415161713 unmodified lines3132333435363738394041424344454647484950515253545556575859606162636465666768697071727316 unmodified lines90919293949531 unmodified lines12712812913013113213313413513613713813914014114260 unmodified lines2032042052062072082094 unmodified lines21421521621721821922022122222322422522622722822923023123223323423523676 unmodified lines3133143153163173183191 unmodified line32132232332432532632732832933033133233333433533633733833934034134234334434534627 unmodified lines3743753763773783793803 unmodified lines3843853863873883893903913923933943953963973983994004014026 unmodified lines40941041141241341441541641715 unmodified lines4334344354364374384394404414424434444454464474484494 unmodified lines45445545645745845946046 unmodified lines50750850951051151251351451551651751851952052152252352411 unmodified linesimport gradio as grimport boto3import tempfilefrom botocore.client import Configfrom PIL import Image13 unmodified linesR2_ENDPOINT = OneKey[6]tmpFolder = "tmp"os.makedirs(tmpFolder, exist_ok=True)def upload_user_img(clientIp, timeId, img):fileName = clientIp.replace(".", "")+str(timeId)+".jpg"local_path = os.path.join(tmpFolder, fileName)img = cv2.imread(img)cv2.imwrite(os.path.join(tmpFolder, fileName), img)json_data = {"token": TOKEN,"input1": fileName,"input2": "","protocol": "","cloud": "ali"}session = requests.session()ret = requests.post(f"{UKAPIURL}/upload",headers={'Content-Type': 'application/json'},json=json_data)res = ""if ret.status_code==200:if 'upload1' in ret.json():upload_url = ret.json()['upload1']headers = {'Content-Type': 'image/jpeg'}response = session.put(upload_url, data=open(local_path, 'rb').read(), headers=headers)# print(response.status_code)if response.status_code == 200:res = upload_urlif os.path.exists(local_path):os.remove(local_path)return resclass R2Api:16 unmodified linesself.session = requests.Session() if session is None else sessiondef upload_file(self, local_path, cloud_path):t1 = time.time()head_dict = {31 unmodified linesprint("upload_file time is ====>", time.time() - t1)return f"{self.domain}{cloud_path}"def upload_user_img_r2(clientIp, timeId, img):fileName = clientIp.replace(".", "")+str(timeId)+".jpg"local_path = os.path.join(tmpFolder, fileName)img = cv2.imread(img)cv2.imwrite(os.path.join(tmpFolder, fileName), img)res = R2Api().upload_file(local_path, fileName)if os.path.exists(local_path):os.remove(local_path)return res60 unmodified linesdef upload_mask_image_r2(client_ip, time_id, mask_image):"""Upload mask image to R2Args:client_ip (str): Client IP4 unmodified linesstr: Uploaded URL"""file_name = f"{client_ip.replace('.', '')}{time_id}_mask.png"local_path = os.path.join(tmpFolder, file_name)try:# Save mask image as PNG format (supports transparency)mask_image.save(local_path, 'PNG')# Upload to R2res = R2Api().upload_file(local_path, file_name)return resexcept Exception as e:print(f"Failed to upload mask image: {e}")return Nonefinally:# Clean up local filesif os.path.exists(local_path):os.remove(local_path)76 unmodified linesprompt: Editing instructionsprogress_callback: Progress callback function"""temp_img_path = Nonetry:# Generate client IP and timestampclient_ip = "127.0.0.1" # Default IP1 unmodified line# Process input image - supports PIL Image and file pathif hasattr(img_input, 'save'): # PIL Image object# Create temporary filetemp_dir = tempfile.mkdtemp()temp_img_path = os.path.join(temp_dir, f"temp_img_{time_id}.jpg")# Save PIL Image as temporary fileif img_input.mode != 'RGB':img_input = img_input.convert('RGB')img_input.save(temp_img_path, 'JPEG', quality=95)img_path = temp_img_pathprint(f"💾 PIL Image saved as temporary file: {temp_img_path}")else:# Assume it's a file pathimg_path = img_inputif progress_callback:progress_callback("uploading image...")# Upload user imageuploaded_url = upload_user_img_r2(client_ip, time_id, img_path)if not uploaded_url:return None, "image upload failed"27 unmodified lineselif status in ['queued', 'processing', 'running', 'created', 'working']:if progress_callback:progress_callback(f"task processing... (status: {status})")time.sleep(1) # 等待10秒后重试else:if progress_callback:progress_callback(f"unknown status: {status}")3 unmodified linesexcept Exception as e:return None, f"error occurred during processing: {str(e)}"finally:# 清理临时文件if temp_img_path and os.path.exists(temp_img_path):try:os.remove(temp_img_path)# 尝试删除临时目录(如果为空)temp_dir = os.path.dirname(temp_img_path)if os.path.exists(temp_dir):os.rmdir(temp_dir)print(f"🗑️ Cleaned up temporary file: {temp_img_path}")except Exception as cleanup_error:print(f"⚠️ Failed to clean up temporary file: {cleanup_error}")def process_local_image_edit(base_image, layers, prompt, progress_callback=None):6 unmodified linesprompt (str): 编辑指令progress_callback: 进度回调函数"""temp_img_path = Nonetemp_mask_path = Nonetry:# Generate client IP and timestampclient_ip = "127.0.0.1" # Default IP15 unmodified linesif progress_callback:progress_callback("uploading original image...")# 处理并上传原始图片temp_dir = tempfile.mkdtemp()temp_img_path = os.path.join(temp_dir, f"temp_img_{time_id}.jpg")# 保存原始图片if base_image.mode != 'RGB':base_image = base_image.convert('RGB')base_image.save(temp_img_path, 'JPEG', quality=95)# 上传原始图片uploaded_url = upload_user_img_r2(client_ip, time_id, temp_img_path)if not uploaded_url:return None, "original image upload failed"4 unmodified linesif progress_callback:progress_callback("uploading mask image...")# 上传mask图片mask_url = upload_mask_image_r2(client_ip, time_id, mask_image)if not mask_url:return None, "mask image upload failed"46 unmodified linesexcept Exception as e:print(f"❌ 局部编辑处理异常: {str(e)}")return None, f"error occurred during processing: {str(e)}"finally:# 清理临时文件if temp_img_path and os.path.exists(temp_img_path):try:os.remove(temp_img_path)temp_dir = os.path.dirname(temp_img_path)if os.path.exists(temp_dir):os.rmdir(temp_dir)print(f"🗑️ Cleaned up temporary file: {temp_img_path}")except Exception as cleanup_error:print(f"⚠️ Failed to clean up temporary file: {cleanup_error}")if __name__ == "__main__":11 unmodified lines1213141516171813 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757616 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213331 unmodified lines16516616716816917017117217317417517617717817918018118218318418518618718818919019119219360 unmodified lines2542552562572582592604 unmodified lines26526626726826927027127227327427527627727827928028128228328476 unmodified lines3613623633643653661 unmodified line36836937037137237337437537637737837938038138238338438527 unmodified lines4134144154164174184193 unmodified lines4234244254264274286 unmodified lines43543643743843944015 unmodified lines4564574584594604614624634 unmodified lines46846947047147247347446 unmodified lines52152252352452552611 unmodified linesimport gradio as grimport boto3import tempfileimport iofrom botocore.client import Configfrom PIL import Image13 unmodified linesR2_ENDPOINT = OneKey[6]# tmpFolder is no longer needed since we upload directly from memory# tmpFolder = "tmp"# os.makedirs(tmpFolder, exist_ok=True)# Legacy function - no longer used since we upload directly from memory# def upload_user_img(clientIp, timeId, img):# fileName = clientIp.replace(".", "")+str(timeId)+".jpg"# local_path = os.path.join(tmpFolder, fileName)# img = cv2.imread(img)# cv2.imwrite(os.path.join(tmpFolder, fileName), img)## json_data = {# "token": TOKEN,# "input1": fileName,# "input2": "",# "protocol": "",# "cloud": "ali"# }## session = requests.session()# ret = requests.post(# f"{UKAPIURL}/upload",# headers={'Content-Type': 'application/json'},# json=json_data# )## res = ""# if ret.status_code==200:# if 'upload1' in ret.json():# upload_url = ret.json()['upload1']# headers = {'Content-Type': 'image/jpeg'}# response = session.put(upload_url, data=open(local_path, 'rb').read(), headers=headers)# # print(response.status_code)# if response.status_code == 200:# res = upload_url# if os.path.exists(local_path):# os.remove(local_path)# return resclass R2Api:16 unmodified linesself.session = requests.Session() if session is None else sessiondef upload_from_memory(self, image_data, filename, content_type='image/jpeg'):"""Upload image data directly from memory to R2Args:image_data (bytes): Image data in bytesfilename (str): Filename for the uploaded filecontent_type (str): MIME type of the imageReturns:str: URL of the uploaded file"""t1 = time.time()headers = {"Content-Type": content_type}cloud_path = f"QwenImageEdit/Uploads/{str(datetime.date.today())}/{filename}"url = self.client.generate_presigned_url("put_object",Params={"Bucket": self.R2_BUCKET, "Key": cloud_path, "ContentType": content_type},ExpiresIn=604800)retry_count = 0while retry_count < 3:try:self.session.put(url, data=image_data, headers=headers, timeout=8)breakexcept (requests.exceptions.Timeout, requests.exceptions.RequestException):retry_count += 1if retry_count == 3:raise Exception('Failed to upload file to R2 after 3 retries!')continueprint("upload_from_memory time is ====>", time.time() - t1)return f"{self.domain}{cloud_path}"def upload_file(self, local_path, cloud_path):t1 = time.time()head_dict = {31 unmodified linesprint("upload_file time is ====>", time.time() - t1)return f"{self.domain}{cloud_path}"def upload_user_img_r2(clientIp, timeId, pil_image):"""Upload PIL Image directly to R2 without saving to local fileArgs:clientIp (str): Client IP addresstimeId (int): Timestamppil_image (PIL.Image): PIL Image objectReturns:str: Uploaded URL"""fileName = clientIp.replace(".", "")+str(timeId)+".jpg"# Convert PIL Image to bytesimg_buffer = io.BytesIO()if pil_image.mode != 'RGB':pil_image = pil_image.convert('RGB')pil_image.save(img_buffer, format='JPEG', quality=95)img_data = img_buffer.getvalue()# Upload directly from memoryres = R2Api().upload_from_memory(img_data, fileName, 'image/jpeg')return res60 unmodified linesdef upload_mask_image_r2(client_ip, time_id, mask_image):"""Upload mask image to R2 directly from memoryArgs:client_ip (str): Client IP4 unmodified linesstr: Uploaded URL"""file_name = f"{client_ip.replace('.', '')}{time_id}_mask.png"try:# Convert mask image to bytesimg_buffer = io.BytesIO()mask_image.save(img_buffer, format='PNG')img_data = img_buffer.getvalue()# Upload directly from memoryres = R2Api().upload_from_memory(img_data, file_name, 'image/png')return resexcept Exception as e:print(f"Failed to upload mask image: {e}")return None76 unmodified linesprompt: Editing instructionsprogress_callback: Progress callback function"""try:# Generate client IP and timestampclient_ip = "127.0.0.1" # Default IP1 unmodified line# Process input image - supports PIL Image and file pathif hasattr(img_input, 'save'): # PIL Image objectpil_image = img_inputprint(f"💾 Using PIL Image directly from memory")else:# Load from file pathpil_image = Image.open(img_input)print(f"📁 Loaded image from file: {img_input}")if progress_callback:progress_callback("uploading image...")# Upload user image directly from memoryuploaded_url = upload_user_img_r2(client_ip, time_id, pil_image)if not uploaded_url:return None, "image upload failed"27 unmodified lineselif status in ['queued', 'processing', 'running', 'created', 'working']:if progress_callback:progress_callback(f"task processing... (status: {status})")time.sleep(1)else:if progress_callback:progress_callback(f"unknown status: {status}")3 unmodified linesexcept Exception as e:return None, f"error occurred during processing: {str(e)}"def process_local_image_edit(base_image, layers, prompt, progress_callback=None):6 unmodified linesprompt (str): 编辑指令progress_callback: 进度回调函数"""try:# Generate client IP and timestampclient_ip = "127.0.0.1" # Default IP15 unmodified linesif progress_callback:progress_callback("uploading original image...")# 直接从内存上传原始图片uploaded_url = upload_user_img_r2(client_ip, time_id, base_image)if not uploaded_url:return None, "original image upload failed"4 unmodified linesif progress_callback:progress_callback("uploading mask image...")# 直接从内存上传mask图片mask_url = upload_mask_image_r2(client_ip, time_id, mask_image)if not mask_url:return None, "mask image upload failed"46 unmodified linesexcept Exception as e:print(f"❌ 局部编辑处理异常: {str(e)}")return None, f"error occurred during processing: {str(e)}"if __name__ == "__main__":
util.py+115-113