From 5b0b582039773690597eec2a54fc26c9a9760fd5 Mon Sep 17 00:00:00 2001 From: Marc-Andre Ferland Date: Mon, 17 Oct 2022 22:35:51 -0400 Subject: [PATCH 1/2] Force encoding to utf-8 on text file operations Fixes #332 --- ui/sd_internal/runtime.py | 2 +- ui/server.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ui/sd_internal/runtime.py b/ui/sd_internal/runtime.py index 0b0a3003..ae7060d3 100644 --- a/ui/sd_internal/runtime.py +++ b/ui/sd_internal/runtime.py @@ -541,7 +541,7 @@ Negative Prompt: {req.negative_prompt} Stable Diffusion Model: {req.use_stable_diffusion_model + '.ckpt'} """ try: - with open(meta_out_path, 'w') as f: + with open(meta_out_path, 'w', encoding='utf-8') as f: f.write(metadata) except: print('could not save the file', traceback.format_exc()) diff --git a/ui/server.py b/ui/server.py index a803ceb9..46738ae4 100644 --- a/ui/server.py +++ b/ui/server.py @@ -187,13 +187,13 @@ async def setAppConfig(req : SetAppConfigRequest): config_bat_path = os.path.join(CONFIG_DIR, 'config.bat') config_sh_path = os.path.join(CONFIG_DIR, 'config.sh') - with open(config_json_path, 'w') as f: + with open(config_json_path, 'w', encoding='utf-8') as f: f.write(config_json_str) - with open(config_bat_path, 'w') as f: + with open(config_bat_path, 'w', encoding='utf-8') as f: f.write(config_bat_str) - with open(config_sh_path, 'w') as f: + with open(config_sh_path, 'w', encoding='utf-8') as f: f.write(config_sh_str) return {'OK'} @@ -206,7 +206,7 @@ def getConfig(default_val={}): config_json_path = os.path.join(CONFIG_DIR, 'config.json') if not os.path.exists(config_json_path): return default_val - with open(config_json_path, 'r') as f: + with open(config_json_path, 'r', encoding='utf-8') as f: return json.load(f) except Exception as e: print(str(e)) @@ -216,7 +216,7 @@ def getConfig(default_val={}): def setConfig(config): try: config_json_path = os.path.join(CONFIG_DIR, 'config.json') - with open(config_json_path, 'w') as f: + with open(config_json_path, 'w', encoding='utf-8') as f: return json.dump(config, f) except: print(str(e)) From 89b1b6e242aa07355b8935ace720eebec49c8702 Mon Sep 17 00:00:00 2001 From: Marc-Andre Ferland Date: Tue, 18 Oct 2022 02:30:30 -0400 Subject: [PATCH 2/2] Replaced 'return HTTPException' by 'raise HTTPException' --- ui/server.py | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/ui/server.py b/ui/server.py index 46738ae4..48b364f1 100644 --- a/ui/server.py +++ b/ui/server.py @@ -80,9 +80,9 @@ def read_root(): @app.get('/ping') # Get server and optionally session status. def ping(session_id:str=None): if not task_manager.render_thread.is_alive(): # Render thread is dead. - if task_manager.current_state_error: return HTTPException(status_code=500, detail=str(current_state_error)) - return HTTPException(status_code=500, detail='Render thread is dead.') - if task_manager.current_state_error and not isinstance(task_manager.current_state_error, StopAsyncIteration): return HTTPException(status_code=500, detail=str(current_state_error)) + if task_manager.current_state_error: raise HTTPException(status_code=500, detail=str(current_state_error)) + raise HTTPException(status_code=500, detail='Render thread is dead.') + if task_manager.current_state_error and not isinstance(task_manager.current_state_error, StopAsyncIteration): raise HTTPException(status_code=500, detail=str(current_state_error)) # Alive response = {'status': str(task_manager.current_state)} if session_id: @@ -125,23 +125,23 @@ def render(req : task_manager.ImageRequest): } return JSONResponse(response, headers=NOCACHE_HEADERS) except ChildProcessError as e: # Render thread is dead - return HTTPException(status_code=500, detail=f'Rendering thread has died.') # HTTP500 Internal Server Error + raise HTTPException(status_code=500, detail=f'Rendering thread has died.') # HTTP500 Internal Server Error except ConnectionRefusedError as e: # Unstarted task pending, deny queueing more than one. - return HTTPException(status_code=503, detail=f'Session {req.session_id} has an already pending task.') # HTTP503 Service Unavailable + raise HTTPException(status_code=503, detail=f'Session {req.session_id} has an already pending task.') # HTTP503 Service Unavailable except Exception as e: - return HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=str(e)) @app.get('/image/stream/{session_id:str}/{task_id:int}') def stream(session_id:str, task_id:int): #TODO Move to WebSockets ?? task = task_manager.task_cache.tryGet(session_id) - if not task: return HTTPException(status_code=410, detail='No request received.') # HTTP410 Gone - if (id(task) != task_id): return HTTPException(status_code=409, detail=f'Wrong task id received. Expected:{id(task)}, Received:{task_id}') # HTTP409 Conflict + if not task: raise HTTPException(status_code=410, detail='No request received.') # HTTP410 Gone + if (id(task) != task_id): raise HTTPException(status_code=409, detail=f'Wrong task id received. Expected:{id(task)}, Received:{task_id}') # HTTP409 Conflict if task.buffer_queue.empty() and not task.lock.locked(): if task.response: #print(f'Session {session_id} sending cached response') return JSONResponse(task.response, headers=NOCACHE_HEADERS) - return HTTPException(status_code=425, detail='Too Early, task not started yet.') # HTTP425 Too Early + raise HTTPException(status_code=425, detail='Too Early, task not started yet.') # HTTP425 Too Early #print(f'Session {session_id} opened live render stream {id(task.buffer_queue)}') return StreamingResponse(task.read_buffer_generator(), media_type='application/json') @@ -149,20 +149,20 @@ def stream(session_id:str, task_id:int): def stop(session_id:str=None): if not session_id: if task_manager.current_state == task_manager.ServerStates.Online or task_manager.current_state == task_manager.ServerStates.Unavailable: - return HTTPException(status_code=409, detail='Not currently running any tasks.') # HTTP409 Conflict + raise HTTPException(status_code=409, detail='Not currently running any tasks.') # HTTP409 Conflict task_manager.current_state_error = StopAsyncIteration('') return {'OK'} task = task_manager.task_cache.tryGet(session_id) - if not task: return HTTPException(status_code=404, detail=f'Session {session_id} has no active task.') # HTTP404 Not Found - if isinstance(task.error, StopAsyncIteration): return HTTPException(status_code=409, detail=f'Session {session_id} task is already stopped.') # HTTP409 Conflict + if not task: raise HTTPException(status_code=404, detail=f'Session {session_id} has no active task.') # HTTP404 Not Found + if isinstance(task.error, StopAsyncIteration): raise HTTPException(status_code=409, detail=f'Session {session_id} task is already stopped.') # HTTP409 Conflict task.error = StopAsyncIteration('') return {'OK'} @app.get('/image/tmp/{session_id}/{img_id:int}') def get_image(session_id, img_id): task = task_manager.task_cache.tryGet(session_id) - if not task: return HTTPException(status_code=410, detail=f'Session {session_id} has not submitted a task.') # HTTP410 Gone - if not task.temp_images[img_id]: return HTTPException(status_code=425, detail='Too Early, task data is not available yet.') # HTTP425 Too Early + if not task: raise HTTPException(status_code=410, detail=f'Session {session_id} has not submitted a task.') # HTTP410 Gone + if not task.temp_images[img_id]: raise HTTPException(status_code=425, detail='Too Early, task data is not available yet.') # HTTP425 Too Early try: img_data = task.temp_images[img_id] if isinstance(img_data, str): @@ -170,7 +170,7 @@ def get_image(session_id, img_id): img_data.seek(0) return StreamingResponse(img_data, media_type='image/jpeg') except KeyError as e: - return HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=str(e)) @app.post('/app_config') async def setAppConfig(req : SetAppConfigRequest): @@ -199,7 +199,7 @@ async def setAppConfig(req : SetAppConfigRequest): return {'OK'} except Exception as e: print(traceback.format_exc()) - return HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=str(e)) def getConfig(default_val={}): try: @@ -254,18 +254,18 @@ def getModels(): @app.get('/get/{key:path}') def read_web_data(key:str=None): if not key: # /get without parameters, stable-diffusion easter egg. - return HTTPException(status_code=418, detail="StableDiffusion is drawing a teapot!") # HTTP418 I'm a teapot + raise HTTPException(status_code=418, detail="StableDiffusion is drawing a teapot!") # HTTP418 I'm a teapot elif key == 'app_config': config = getConfig(default_val=None) if config is None: - return HTTPException(status_code=500, detail="Config file is missing or unreadable") + raise HTTPException(status_code=500, detail="Config file is missing or unreadable") return JSONResponse(config, headers=NOCACHE_HEADERS) elif key == 'models': return JSONResponse(getModels(), headers=NOCACHE_HEADERS) elif key == 'modifiers': return FileResponse(os.path.join(SD_UI_DIR, 'modifiers.json'), headers=NOCACHE_HEADERS) elif key == 'output_dir': return JSONResponse({ 'output_dir': outpath }, headers=NOCACHE_HEADERS) else: - return HTTPException(status_code=404, detail=f'Request for unknown {key}') # HTTP404 Not Found + raise HTTPException(status_code=404, detail=f'Request for unknown {key}') # HTTP404 Not Found # don't log certain requests class LogSuppressFilter(logging.Filter):