support payment

This commit is contained in:
RiceRound
2025-02-20 10:28:17 +08:00
parent 759b07e947
commit cb978ae132
11 changed files with 92 additions and 77 deletions
+3 -1
View File
@@ -113,11 +113,13 @@ async def install_choice_node(request):
return aiohttp.web.json_response({_A:_B,A:'Installation successful, server will restart in 3 seconds'},status=200)
return aiohttp.web.json_response({_A:B,A:'Installation failed'},status=400)
is_on_riceround=False
client_random=None
if os.getenv('RICE_ROUND_SERVER')=='true':is_on_riceround=True
if is_on_riceround:client_random=os.getenv('RICE_ROUND_CLIENT_RANDOM')
@web.middleware
async def check_login_status(request,handler):
if is_on_riceround:
if request.headers.get('owner')=='share_client':return await handler(request)
if request.headers.get('owner')=='share_client'and request.headers.get('client_random')==client_random:return await handler(request)
return web.json_response({_C:'Access denied'},status=403)
return await handler(request)
if not is_on_riceround:
+8 -8
View File
@@ -19,20 +19,20 @@ class AuthUnit:
A.token='';A.last_check_time=0
if need_clear:A.clear_user_token()
def get_user_token(A):
H='message';G='user_id';A.token=A.read_user_token()
F='message';A.token=A.read_user_token()
if time.time()-A.last_check_time>120 and A.token and len(A.token)>50:
try:
I={'Content-Type':'application/json','Authorization':f"Bearer {A.token}"};B=requests.get(RiceUrlConfig().get_info_url,headers=I,timeout=10)
G={'Content-Type':'application/json','Authorization':f"Bearer {A.token}"};B=requests.get(RiceUrlConfig().get_info_url,headers=G,timeout=10)
if B.status_code==200:
E=B.json()
if G in E:A.user_id=E[G]
else:A.user_id=0
H=B.json()
try:A.user_id=int(H.get('user_id',0)or 0)
except(ValueError,TypeError):A.user_id=0
A.last_check_time=time.time();return A.token,'',RiceRoundErrorDef.SUCCESS
else:
C='登录结果错误';D=RiceRoundErrorDef.UNKNOWN_ERROR
try:
F=B.json()
if H in F:C=F[H]
E=B.json()
if F in E:C=E[F]
except ValueError:pass
if B.status_code==401:C='登录已过期,请重新登录';D=RiceRoundErrorDef.HTTP_UNAUTHORIZED
elif B.status_code==500:C='服务器内部错误,请稍后重试';D=RiceRoundErrorDef.HTTP_INTERNAL_ERROR
@@ -40,7 +40,7 @@ class AuthUnit:
A.empty_token(B.status_code==401);return _A,C,D
except requests.exceptions.Timeout:A.empty_token();return _A,'请求超时,请检查网络连接',RiceRoundErrorDef.HTTP_TIMEOUT
except requests.exceptions.ConnectionError:A.empty_token();return _A,'网络连接失败,请检查网络',RiceRoundErrorDef.NETWORK_ERROR
except requests.exceptions.RequestException as J:A.empty_token();return _A,f"请求失败: {str(J)}",RiceRoundErrorDef.REQUEST_ERROR
except requests.exceptions.RequestException as I:A.empty_token();return _A,f"请求失败: {str(I)}",RiceRoundErrorDef.REQUEST_ERROR
if A.token and len(A.token)>50:return A.token,'',RiceRoundErrorDef.SUCCESS
return _A,'未读取到有效的token,请重新登录',RiceRoundErrorDef.NO_TOKEN_ERROR
def get_user_info(A):
+28 -28
View File
@@ -12,15 +12,15 @@ _p='hidden'
_o='required'
_n='RiceRoundInputTextNode'
_m='RiceRoundDecryptNode'
_l='main_link_id'
_k='slot_index'
_j='task_id'
_i='PNG'
_h='images'
_g='template_id'
_f='RiceRoundAdvancedChoiceNode'
_e='RiceRoundSimpleChoiceNode'
_d='title'
_l='title'
_k='main_link_id'
_j='slot_index'
_i='task_id'
_h='PNG'
_g='images'
_f='template_id'
_e='RiceRoundAdvancedChoiceNode'
_d='RiceRoundSimpleChoiceNode'
_c='_meta'
_b=True
_a='extra_pnginfo'
@@ -66,11 +66,11 @@ from server import PromptServer
from.rice_url_config import RiceUrlConfig
from.rice_prompt_info import RicePromptInfo
output_project_folder=folder_paths.output_directory
INPUT_NODE_TYPES=[_e,_f,_O,_P,_L,_Q,_n,_R,_S,_T,_U,_V,_W,_X,_Y]
INPUT_NODE_TYPES=[_d,_e,_O,_P,_L,_Q,_n,_R,_S,_T,_U,_V,_W,_X,_Y]
class RiceRoundEncryptNode:
def __init__(A):A.template_id=uuid.uuid4().hex;A.output_dir=folder_paths.get_temp_directory();A.type='temp';A.prefix_append='_temp_'+''.join(random.choice('abcdefghijklmnopqrstupvxyz')for A in range(5));A.compress_level=4
@classmethod
def INPUT_TYPES(A):return{_o:{_q:(_E,{_I:'my_project'}),_g:(_E,{_I:uuid.uuid4().hex}),_h:(_J,)},_p:{_M:_r,_Z:_s,_a:_t}}
def INPUT_TYPES(A):return{_o:{_q:(_E,{_I:'my_project'}),_f:(_E,{_I:uuid.uuid4().hex}),_g:(_J,)},_p:{_M:_r,_Z:_s,_a:_t}}
@classmethod
def IS_CHANGED(A,**B):return float('NaN')
RETURN_TYPES=();OUTPUT_NODE=_b;FUNCTION='encrypt';CATEGORY='RiceRound'
@@ -79,7 +79,7 @@ class RiceRoundEncryptNode:
for(I,a)in enumerate(A):
b=255.*a.cpu().numpy();J=Image.fromarray(np.clip(b,0,255).astype(np.uint8))
if I==0:H=os.path.join(F,'preview.png');J.save(H)
Z.update_absolute(I,A.shape[0],(_i,J,_B));c=X.replace('%batch_num%',str(I));N=f"{c}_{L:05}_.png";J.save(os.path.join(W,N),compress_level=B.compress_level);M.append({'filename':N,'subfolder':Y,_A:B.type});L+=1
Z.update_absolute(I,A.shape[0],(_h,J,_B));c=X.replace('%batch_num%',str(I));N=f"{c}_{L:05}_.png";J.save(os.path.join(W,N),compress_level=B.compress_level);M.append({'filename':N,'subfolder':Y,_A:B.type});L+=1
d=RicePromptInfo().get_auto_publish()
if d:
e=Publish(F);O,P,C=AuthUnit().get_user_token()
@@ -92,11 +92,11 @@ class RiceRoundEncryptNode:
if RicePromptInfo().get_run_client():
C,P=RiceInstallClient().run_client()
if C!=RiceRoundErrorDef.SUCCESS:PromptServer.instance.send_sync(Q,{R:'加密节点发布完成,但无法启动client,建议官网重新安装',_A:S})
return{'ui':{_h:M}}
return{'ui':{_g:M}}
class RiceRoundOutputImageNode:
def __init__(A):A.url_config=RiceUrlConfig()
@classmethod
def INPUT_TYPES(A):return{_o:{_h:(_J,),_j:(_E,{_I:''})},'optional':{_g:(_E,{_I:''})},_p:{_M:_r,_Z:_s,_a:_t}}
def INPUT_TYPES(A):return{_o:{_g:(_J,),_i:(_E,{_I:''})},'optional':{_f:(_E,{_I:''})},_p:{_M:_r,_Z:_s,_a:_t}}
RETURN_TYPES=();OUTPUT_NODE=_b;FUNCTION='load';CATEGORY='__hidden__'
def load(N,images,task_id,template_id,**B):
I='image_type';C=images;A=task_id;D=B.pop(_M,_B);J=B.pop(_Z,_B);O=B.pop(_a,_B);E=PromptServer.instance.client_id;F=''
@@ -107,12 +107,12 @@ class RiceRoundOutputImageNode:
else:
print(f"RiceRoundOutputImageNode task_id: {A}")
if C.shape[0]>5:raise ValueError('Error: Cannot upload more than 5 images.')
G=[];time.sleep(60)
G=[]
for K in C:
H=machine_upload_image(K,A)
if not H:raise ValueError('Error: Failed to upload image.')
G.append(H)
L={I:_i,'image_results':G};M={_j:A,_M:D,'client_id':E,'prompt_id':F,'timestamp':int(time.time()*1000),I:_i,'result_data':L};PromptServer.instance.send_sync('rice_round_done',M,sid=E)
L={I:_h,'image_results':G};M={_i:A,_M:D,'client_id':E,'prompt_id':F,'timestamp':int(time.time()*1000),I:_h,'result_data':L};PromptServer.instance.send_sync('rice_round_done',M,sid=E)
return{}
class Encrypt:
def __init__(A,workflow,prompt,project_name,template_id):
@@ -133,7 +133,7 @@ class Encrypt:
for D in G:
E=D.get(_C,[])
if not E:continue
for B in E:B=int(B);A.link_owner_map[B][_C]=copy.deepcopy(E);A.link_owner_map[B][_k]=D.get(_k,0);A.link_owner_map[B][_u]=int(F[_D]);A.link_owner_map[B][_A]=D.get(_A,'')
for B in E:B=int(B);A.link_owner_map[B][_C]=copy.deepcopy(E);A.link_owner_map[B][_j]=D.get(_j,0);A.link_owner_map[B][_u]=int(F[_D]);A.link_owner_map[B][_A]=D.get(_A,'')
A.last_node_id=int(C[_v]);A.last_link_id=int(C['last_link_id'])
def load_prompt(A):B=copy.deepcopy(A.original_prompt);A.node_prompt_map={int(A):B for(A,B)in B.items()}
def analyze_input_from_workflow(A):
@@ -144,7 +144,7 @@ class Encrypt:
if not C:continue
D=C[0].get(_C,[])
if not D:continue
F=int(D[0]);A.input_node_map[id][_l]=F;A.input_node_map[id][_w]=C[0].get(_A,_E)
F=int(D[0]);A.input_node_map[id][_k]=F;A.input_node_map[id][_w]=C[0].get(_A,_E)
A.input_node_map={A:B for(A,B)in sorted(A.input_node_map.items(),key=lambda x:x[0])}
def assemble_new_workflow(A):C=list(A.input_node_map.keys());B=copy.deepcopy(A.original_workflow);A.related_node_ids=A.find_workflow_related_nodes(B[_C],C);B[_F]=[B for B in B[_F]if int(B[_D])in A.related_node_ids];A.invalid_new_workflow(B);D=A.add_decrypt_node(B);A.remove_redundant_links(B);A.remove_unrelated_nodes(B,A.related_node_ids,D);A.replace_choice_template(B);A.replace_workflow_node(B);A.output_file(B,f"{A.template_id}_workflow")
def output_template_json_file(F):
@@ -156,20 +156,20 @@ class Encrypt:
Q=RicePromptInfo();R=[]
for(G,W)in F.input_node_map.items():
X=W[_x];B=F.workflow_nodes_dict[G][_A];D=F.node_prompt_map[G].get(_H,{});H=str(D.get(_K,''))
if not H:H=F.node_prompt_map[G].get(_c,{}).get(_d,'')
if not H:H=F.node_prompt_map[G].get(_c,{}).get(_l,'')
A={_D:str(X),_A:'',C:'输入组件','node_id':str(G),E:{}}
if B in[_O,_L,_Q]:A[_A]='image_upload';A[C]='请上传图片';A[E]={M:P,N:500000,O:S}
elif B==_P:A[_A]='mask_image_upload';A[C]='请上传图片并编辑蒙版';A[E]={M:P,N:500000,O:S,'mask':_b}
elif B in[_R,_S]:A[_A]='mask_upload';A[C]='请上传蒙版';A[E]={M:P,N:50000,O:'请上传不超过50KB的图片'}
elif B==_n:A[_A]='text';A[C]='提示词';A[E]={'placeholder':'请描述图片内容','multiline':_b}
elif B==_e or B==_f:A[_A]='choice';A[C]='模型选择';A[E]={'options':Q.get_choice_value(G),_I:D.get(_I,'')};A['addition']=Q.get_choice_node_addition(G)
elif B==_d or B==_e:A[_A]='choice';A[C]='模型选择';A[E]={'options':Q.get_choice_value(G),_I:D.get(_I,'')};A['addition']=Q.get_choice_node_addition(G)
elif B==_T or B==_V:A[_A]='number_int';A[C]='数值';A[E]={I:D.get(I,0),J:D.get(J,1000),K:D.get(K,0)}
elif B==_U or B==_W:A[_A]='number_float';A[C]='数值';A[E]={I:D.get(I,.0),J:D.get(J,1e3),K:D.get(K,.0)}
elif B==_X or B==_Y:A[_A]='switch';A[C]='开关';A[E]={_I:D.get('value',False)}
else:raise ValueError(f"Error: The node {G} is not a valid RiceRound node.")
if H and H not in L:A[C]=H
R.append(A)
Y={_g:F.template_id,_d:F.project_name,'elements':R};F.output_file(Y,f"{F.template_id}_template")
Y={_f:F.template_id,'elements':R};F.output_file(Y,f"{F.template_id}_template")
def assemble_new_prompt(A):'\n 组装新的prompt配置。主要完成:\n 1. 移除不需要的节点\n 2. 转换特定节点的类型和输入\n 3. 保存处理后的prompt配置\n ';B=A._create_filtered_prompt();A._replace_encrypt_node(B);A._transform_node_types(B);A.output_file(B,f"{A.template_id}_job")
def _create_filtered_prompt(B):
'\n 创建经过过滤的prompt副本,移除不需要的节点\n ';A=copy.deepcopy(B.original_prompt);C=B._get_exclude_node_ids(A)
@@ -180,8 +180,8 @@ class Encrypt:
for(E,A)in new_prompt.items():
B=A.get(_N,'');print(f"class_type: {B}")
if B=='RiceRoundEncryptNode':
A[_N]=C;A[_H][_j]='';A[_H].pop(_q,_B)
if _c in A and _d in A[_c]:A[_c][_d]=C
A[_N]=C;A[_H][_i]='';A[_H].pop(_q,_B)
if _c in A and _l in A[_c]:A[_c][_l]=C
def save_rice_zip(A):
import pyzipper as B
try:
@@ -208,9 +208,9 @@ class Encrypt:
J=F[G];C[_N]=J[A];C[_H]=J[B].copy()
if I:C[_H][_K]=I
def add_decrypt_node(A,workflow):
K='label';C=workflow;G=set();A.last_node_id+=1;H={_D:A.last_node_id,_A:_m,'pos':[420,0],'size':[500,150],'flags':{},'mode':0,'order':20,_H:[],_G:[{_K:_J,_A:_J,_C:[],K:_J,_k:0}],_y:{_z:_m},'widgets_values':[str(A.template_id),735127949069071,'randomize']}
K='label';C=workflow;G=set();A.last_node_id+=1;H={_D:A.last_node_id,_A:_m,'pos':[420,0],'size':[500,150],'flags':{},'mode':0,'order':20,_H:[],_G:[{_K:_J,_A:_J,_C:[],K:_J,_j:0}],_y:{_z:_m},'widgets_values':[str(A.template_id),735127949069071,'randomize']}
for(B,(D,E))in enumerate(A.input_node_map.items()):
I=E[_l];F=E[_w];E[_x]=B;J={_K:f"input_anything{B if B>0 else''} ({D})",_A:'*','link':I,K:f"input_anything{B if B>0 else''} ({D})"}
I=E[_k];F=E[_w];E[_x]=B;J={_K:f"input_anything{B if B>0 else''} ({D})",_A:'*','link':I,K:f"input_anything{B if B>0 else''} ({D})"}
if B==0:J['shape']=7
H[_H].append(J)
if F not in[_J,_E]:F=_E
@@ -224,7 +224,7 @@ class Encrypt:
for E in A[_F]:
F=int(E[_D])
if F in C.input_node_map:
G=C.input_node_map[F][_l];B=E.get(_G,[])
G=C.input_node_map[F][_k];B=E.get(_G,[])
if not B:continue
for J in B:
H=J.get(_C,[])
@@ -237,13 +237,13 @@ class Encrypt:
D='extra';C=workflow;E=RicePromptInfo()
for A in C[_F]:
B=int(A[_D])
if A.get(_A,'')==_f:
if A.get(_A,'')==_e:
F=E.get_choice_classname(B)
if F:A[_A]=F
else:print(f"Warning: The node {B} is not a valid RiceRound Choice node.")
G={}
for(B,A)in H.input_node_map.items():
if A.get(_A,'')==_e:I=E.get_choice_value(B);G[B]=I
if A.get(_A,'')==_d:I=E.get_choice_value(B);G[B]=I
if D not in C:C[D]={}
C[D]['choice_node_map']=G
def replace_workflow_node(L,workflow):
+1 -1
View File
File diff suppressed because one or more lines are too long
+14 -10
View File
@@ -35,7 +35,7 @@ import requests,numpy as np,folder_paths
from nodes import LoadImage
from comfy.utils import ProgressBar
from server import PromptServer
from.rice_def import RiceRoundErrorDef
from.rice_def import RiceRoundErrorDef,RiceTaskErrorDef
from.rice_url_config import RiceUrlConfig,user_upload_image,user_upload_imagefile
from.utils import get_machine_id,pil2tensor
from.auth_unit import AuthUnit
@@ -85,16 +85,20 @@ class RiceRoundDecryptNode:
L=[]
for O in K:G=Image.open(requests.get(O,stream=_B).raw);G=ImageOps.exif_transpose(G);L.append(pil2tensor(G))
P=torch.cat(L,dim=0);A.pbar=_H;return P,
def create_task(E,input_data,template_id,user_token):
'\n Create a task and return the task UUID.\n \n Args:\n task_url (str): The URL to send the task request to\n request_data (dict): The data to send in the request\n headers (dict): The headers to send with the request\n \n Returns:\n str: The task UUID if successful\n \n Raises:\n ValueError: If the request fails or response is invalid\n ';D='data';F=E.url_config.prompt_task_url;G={_Y:f"Bearer {user_token}",'Content-Type':'application/json'};H={'taskData':json.dumps(input_data),'workData':json.dumps({'template_id':template_id})};A=requests.post(F,json=H,headers=G)
if A.status_code==200:
B=A.json()
if B.get('code')==0 and D in B:
C=TaskInfo(B.get(D,{}))
if C.task_uuid:return C
def create_task(J,input_data,template_id,user_token):
'\n Create a task and return the task UUID.\n \n Args:\n task_url (str): The URL to send the task request to\n request_data (dict): The data to send in the request\n headers (dict): The headers to send with the request\n \n Returns:\n str: The task UUID if successful\n \n Raises:\n ValueError: If the request fails or response is invalid\n ';I='Unknown error';H='message';G='data';F='code';E='template_id';C=template_id;K=J.url_config.prompt_task_url;L={_Y:f"Bearer {user_token}",'Content-Type':'application/json'};M={'taskData':json.dumps(input_data),'workData':json.dumps({E:C})};B=requests.post(K,json=M,headers=L)
if B.status_code==200:
A=B.json()
if A.get(F)==0 and G in A:
D=TaskInfo(A.get(G,{}))
if D.task_uuid:return D
else:raise ValueError('No task UUID in response')
else:raise ValueError(f"API error: {B.get('message','Unknown error')}")
else:raise ValueError(f"HTTP error {A.status_code}: {A.text}")
else:raise ValueError(f"API error: {A.get(H,I)}")
elif B.status_code==RiceRoundErrorDef.HTTP_INTERNAL_ERROR:
A=B.json()
if A.get(F)==RiceTaskErrorDef.ERROR_INSUFFICIENT_PERMISSION_INSUFFICIENT_BALANCE:PromptServer.instance.send_sync('riceround_show_workflow_payment_dialog',{E:C,'title':'余额不足,请充值'});raise ValueError(f"余额不足,运行失败,请完成支付后重试!")
else:raise ValueError(f"API error: {A.get(H,I)}")
else:raise ValueError(f"HTTP error {B.status_code}: {B.text}")
class RiceRoundBaseChoiceNode:
def __init__(A):0
@classmethod
+2 -2
View File
@@ -38,8 +38,8 @@ class Publish:
except Exception as G:return-1,str(G)
def _upload_workflow(I,user_token,template_id,project_name,preview_image_url,publish_file):
try:
C={_B:f"Bearer {user_token}"};D={'templateId':template_id,'title':project_name,'mainImageUrl':preview_image_url or''}
with open(publish_file,'rb')as E:F={'file':('workflow',E,'application/octet-stream')};G={'data':json.dumps(D),'source':'comfyui'};A=requests.put(RiceUrlConfig().publisher_workflow_url,headers=C,files=F,data=G)
C={_B:f"Bearer {user_token}"};D={'template_id':template_id,'title':project_name,'main_image_url':preview_image_url or''}
with open(publish_file,'rb')as E:F={'workflow_file':('workflow',E,'application/octet-stream')};G={'data':json.dumps(D),'source':'comfyui'};A=requests.put(RiceUrlConfig().publisher_workflow_url,headers=C,files=F,data=G)
if A.status_code==200:
B=A.json()
if B.get('code')==0:return True,'Success'
+2 -1
View File
@@ -7,4 +7,5 @@ class RiceRoundErrorDef(IntEnum):
if B<C:
if B!=0:return A+B
else:return A+RiceRoundErrorDef.UNKNOWN_ERROR
else:return A+RiceRoundErrorDef.OVER_MAX_ERROR
else:return A+RiceRoundErrorDef.OVER_MAX_ERROR
class RiceTaskErrorDef(IntEnum):ERROR_FAILED_TO_FETCH_TASK_TEMPLATE=2001;ERROR_INVALID_TASK_TEMPLATE=2002;ERROR_FAILED_TO_GET_QUEUE_COUNT=2003;ERROR_QUEUE_FULL=2004;ERROR_INSUFFICIENT_PERMISSION=2005;ERROR_NO_AVAILABLE_MACHINE=2006;ERROR_FAILED_TO_DEDUCT_BALANCE=2007;ERROR_FAILED_TO_ADD_TASK_TO_QUEUE=2008;ERROR_FAILED_TO_SAVE_TASK_RECORD=2009;ERROR_INSUFFICIENT_PERMISSION_PAYER_ID_INVALID=2051;ERROR_INSUFFICIENT_PERMISSION_PROVIDER_ID_INVALID=2052;ERROR_INSUFFICIENT_PERMISSION_BALANCE_FETCH_FAILED=2053;ERROR_INSUFFICIENT_PERMISSION_INSUFFICIENT_BALANCE=2054
+4 -10
View File
@@ -84,16 +84,10 @@ class RicePromptInfo:
if I and isinstance(H,list):J=copy.deepcopy(B);J[_E]=H;E.choice_classname_map[I]=J
except json.JSONDecodeError as D:print(f"Error parsing JSON from file {A}: {str(D)}")
except Exception as D:print(f"Unexpected error processing file {A}: {str(D)}");continue
def install_choice_node(D,template_id):
A=template_id;B,E,C=AuthUnit().get_user_token()
if not B:
print(f"riceround get user token failed, {E}")
if C==401 or C==-3:AuthUnit().login_dialog('安装节点需要先完成登录')
else:PromptServer.instance.send_sync('riceround_toast',{'content':'无法完成鉴权登录,请检查网络或完成登录步骤','type':'error'})
return _B
F=D.get_choice_server_folder()/f"{A}.json"
try:download_template(A,B,F)
except Exception as G:print(f"failed to download template, {G}");return _B
def install_choice_node(B,template_id):
A=template_id;C,F,G=AuthUnit().get_user_token();D=B.get_choice_server_folder()/f"{A}.json"
try:download_template(A,C,D)
except Exception as E:print(f"failed to download template, {E}");return _B
return _A
def get_choice_node_addition(B,node_id):
A=copy.deepcopy(B.choice_node_map.get(node_id,{}))
+8 -7
View File
@@ -16,7 +16,8 @@ import numpy as np,requests
from urllib.parse import urljoin
from.utils import get_local_app_setting_path
DEFAULT_SUBDOMAIN='api'if os.getenv('RICE_ROUND_DEBUG')!='true'else'test'
DEFAULT_URL_PREFIX=f"https://{DEFAULT_SUBDOMAIN}.riceround.online"
_URL_PREFIX=os.getenv('RICE_ROUND_URL_PREFIX','')
DEFAULT_URL_PREFIX=_URL_PREFIX if _URL_PREFIX and len(_URL_PREFIX)>10 else f"https://{DEFAULT_SUBDOMAIN}.riceround.online"
DEFAULT_WS_PREFIX=f"wss://{DEFAULT_SUBDOMAIN}.riceround.online"
class UploadType(IntEnum):TEMPLATE_PUBLISH_IMAGE=1;USER_UPLOAD_TASK_IMAGE=2;MACHINE_TASK_RESULT=1000
class RiceUrlConfig:
@@ -76,7 +77,7 @@ def user_upload_image(image,user_token):
if A.status_code==200:return B
else:print(f"failed to upload image. Status code: {A.status_code}");raise ValueError(f"failed to upload image. Status code: {A.status_code}")
def machine_upload_image(image,task_id):
F=RiceUrlConfig().machine_upload_sign_url;G=255.*image.cpu().numpy();H=Image.fromarray(np.clip(G,0,255).astype(np.uint8));E=BytesIO();H.save(E,format='PNG',quality=95,compress_level=1);I=E.getvalue();B='';C='';J={_F:UploadType.MACHINE_TASK_RESULT.value,_G:_B,'task_id':task_id};A=requests.get(F,params=J)
E=RiceUrlConfig().machine_upload_sign_url;print(f"upload_image_sign_url: {E}");G=255.*image.cpu().numpy();H=Image.fromarray(np.clip(G,0,255).astype(np.uint8));F=BytesIO();H.save(F,format='PNG',quality=95,compress_level=1);I=F.getvalue();B='';C='';J={_F:UploadType.MACHINE_TASK_RESULT.value,_G:_B,'task_id':task_id};A=requests.get(E,params=J)
if A.status_code==200:
D=A.json()
if D.get(_C)==0:B=D.get(_A,{}).get(_H,'');C=D.get(_A,{}).get(_D,'')
@@ -86,17 +87,17 @@ def machine_upload_image(image,task_id):
if A.status_code==200:return C
else:print(f"failed to upload image. Status code: {A.status_code}, Response: {A.text}");raise ValueError(f"failed to upload image. Status code: {A.status_code}")
def download_template(template_id,user_token,save_path):
F='template_id';B=template_id;H=RiceUrlConfig().workflow_template_url;I={_E:f"Bearer {user_token}"};J={F:B};C=requests.get(H,headers=I,params=J)
G=user_token;F='template_id';B=template_id;I=RiceUrlConfig().workflow_template_url;J={_E:f"Bearer {G}"}if G else{};K={F:B};C=requests.get(I,headers=J,params=K)
if C.status_code!=200:raise ValueError(f"Failed to get template. Status code: {C.status_code}")
D=C.json()
if D.get(_C)!=0:raise ValueError(f"Failed to get template. Error: {D.get('msg')}")
G=D.get(_A,{}).get(_D)
if not G:raise ValueError('Template download URL is empty')
A=requests.get(G)
H=D.get(_A,{}).get(_D)
if not H:raise ValueError('Template download URL is empty')
A=requests.get(H)
if A.status_code!=200:raise ValueError(f"Failed to download template. Status code: {A.status_code}")
try:
E=A.json()
if E.get(F)!=B:raise ValueError(f"Template ID mismatch. Expected: {B}, Got: {E.get(F)}")
with open(save_path,'wb')as K:K.write(A.content)
with open(save_path,'wb')as L:L.write(A.content)
return E
except json.JSONDecodeError:raise ValueError('Failed to parse template JSON data')
+9 -9
View File
@@ -1,17 +1,17 @@
_P='Message'
_O='CommandType'
_N='resultData'
_M='templateName'
_L='templateDescription'
_K='templateId'
_J='updateTime'
_I='createTime'
_N='result_data'
_M='template_name'
_L='template_description'
_K='template_id'
_J='update_time'
_I='create_time'
_H='prompt'
_G='thumbnail'
_F='progressText'
_F='progress_text'
_E='progress'
_D='state'
_C='taskUuid'
_C='task_uuid'
_B=False
_A=None
import datetime
@@ -97,7 +97,7 @@ class TaskWebSocket:
await asyncio.sleep(5)
try:model_management.throw_exception_if_processing_interrupted()
except Exception as B:
print(f"Processing interrupted during progress monitoring: {B}");A.stop_event.set();C=PackageMessage(CommandType=COMMAND_TYPE_USER_CLIENT_WEB_COMMAND_CANCEL_TASK,Message={'task_uuid':A.task_info.task_uuid})
print(f"Processing interrupted during progress monitoring: {B}");A.stop_event.set();C=PackageMessage(CommandType=COMMAND_TYPE_USER_CLIENT_WEB_COMMAND_CANCEL_TASK,Message={_C:A.task_info.task_uuid})
try:await A.send_message(C)
except Exception as D:print(f"Failed to send cancel notification: {D}")
break
File diff suppressed because one or more lines are too long