guardiancc commited on
Commit
fcb6a8f
·
verified ·
1 Parent(s): b768cfd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -95
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import sys
2
  import asyncio
3
  from aiohttp import web, WSMsgType
4
  import json
@@ -12,8 +12,8 @@ from typing import Dict, Any, List, Optional
12
  import base64
13
  import io
14
  from PIL import Image
15
-
16
- import pillow_avif
17
 
18
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
19
  logger = logging.getLogger(__name__)
@@ -26,108 +26,151 @@ signal.signal(signal.SIGSEGV, SIGSEGV_signal_arises)
26
 
27
  from loader import initialize_models
28
  from engine import Engine, base64_data_uri_to_PIL_Image
 
 
 
29
 
30
  # Global constants
31
  DATA_ROOT = os.environ.get('DATA_ROOT', '/tmp/data')
32
  MODELS_DIR = os.path.join(DATA_ROOT, "models")
33
 
34
- class NumpyEncoder(json.JSONEncoder):
35
- def default(self, obj):
36
- if isinstance(obj, np.integer):
37
- return int(obj)
38
- elif isinstance(obj, np.floating):
39
- return float(obj)
40
- elif isinstance(obj, np.ndarray):
41
- return obj.tolist()
42
- else:
43
- return super(NumpyEncoder, self).default(obj)
44
-
45
- async def websocket_handler(request: web.Request) -> web.WebSocketResponse:
46
- ws = web.WebSocketResponse()
47
- await ws.prepare(request)
48
- engine = request.app['engine']
49
- try:
50
- #logger.info("New WebSocket connection established")
51
- while True:
52
- msg = await ws.receive()
53
-
54
- if msg.type in (WSMsgType.CLOSE, WSMsgType.ERROR):
55
- #logger.warning(f"WebSocket connection closed: {msg.type}")
56
- break
57
-
58
- try:
59
- if msg.type == WSMsgType.BINARY:
60
- res = await engine.load_image(msg.data)
61
- json_res = json.dumps(res, cls=NumpyEncoder)
62
- await ws.send_str(json_res)
63
-
64
- elif msg.type == WSMsgType.TEXT:
65
- data = json.loads(msg.data)
66
- webp_bytes = await engine.transform_image(data.get('uuid'), data.get('params'))
67
- await ws.send_bytes(webp_bytes)
68
-
69
- except Exception as e:
70
- logger.error(f"Error in engine: {str(e)}")
71
- logger.exception("Full traceback:")
72
- await ws.send_json({"error": str(e)})
73
-
74
- except Exception as e:
75
- logger.error(f"Error in websocket_handler: {str(e)}")
76
- logger.exception("Full traceback:")
77
- return ws
78
-
79
- async def handle_upload(request: web.Request) -> web.Response:
80
- """Recebe uma imagem e retorna informações sobre ela."""
81
- engine = request.app['engine']
82
- data = await request.content.read()
83
- res = await engine.load_image(data)
84
- return web.json_response(res)
85
-
86
-
87
- async def handle_hello(request: web.Request) -> web.Response:
88
- return web.json_response({
89
- "message": "hello folks!"
90
- })
91
-
92
- async def handle_modify(request: web.Request) -> web.Response:
93
- """Recebe uma imagem e retorna informações sobre ela."""
94
- engine = request.app['engine']
95
- data = await request.json()
96
- webp_bytes = await engine.transform_image(data.get('uuid'), data.get('params'))
97
- return web.Response(body=webp_bytes, content_type="image/webp")
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
- async def initialize_app() -> web.Application:
100
- """Initialize and configure the web application."""
101
- try:
102
- logger.info("Initializing application...")
103
- live_portrait = await initialize_models()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
- logger.info("🚀 Creating Engine instance...")
106
- engine = Engine(live_portrait=live_portrait)
107
- logger.info("✅ Engine instance created.")
 
 
 
 
108
 
109
- app = web.Application()
110
- app['engine'] = engine
111
 
112
- # Configure routes
113
- app.router.add_post("/upload", handle_upload)
114
- app.router.add_post("/modify", handle_modify)
115
- app.router.add_get("/", handle_hello)
 
 
 
116
 
117
- logger.info("Application routes configured")
118
 
119
- return app
120
- except Exception as e:
121
- logger.error(f"🚨 Error during application initialization: {str(e)}")
122
- logger.exception("Full traceback:")
123
- raise
124
 
125
  if __name__ == "__main__":
126
- try:
127
- logger.info("Starting FacePoke application")
128
- app = asyncio.run(initialize_app())
129
- logger.info("Application initialized, starting web server")
130
- web.run_app(app, host="0.0.0.0", port=8080)
131
- except Exception as e:
132
- logger.critical(f"🚨 FATAL: Failed to start the app: {str(e)}")
133
- logger.exception("Full traceback:")
 
1
+ '''import sys
2
  import asyncio
3
  from aiohttp import web, WSMsgType
4
  import json
 
12
  import base64
13
  import io
14
  from PIL import Image
15
+ import gradio as gr
16
+ import cv2
17
 
18
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
19
  logger = logging.getLogger(__name__)
 
26
 
27
  from loader import initialize_models
28
  from engine import Engine, base64_data_uri_to_PIL_Image
29
+ from pathlib import Path
30
+
31
+ import cv2
32
 
33
  # Global constants
34
  DATA_ROOT = os.environ.get('DATA_ROOT', '/tmp/data')
35
  MODELS_DIR = os.path.join(DATA_ROOT, "models")
36
 
37
+ async def setup():
38
+ live_portrait = await initialize_models()
39
+ engine = Engine(live_portrait=live_portrait)
40
+
41
+ def get_all_frames(video_path):
42
+ cap = cv2.VideoCapture(video_path)
43
+
44
+ frames = []
45
+ while True:
46
+ ret, frame = cap.read()
47
+
48
+ if not ret:
49
+ break
50
+
51
+ frames.append(frame)
52
+
53
+ cap.release()
54
+ return frames
55
+
56
+ async def return_image(image):
57
+ binary_data = Path(image).read_bytes()
58
+ res = await engine.load_image(binary_data)
59
+ id = res['u']
60
+ _, image = await engine.transform_image(id, {
61
+ "aaa": -10,
62
+ "eee": -10,
63
+ "woo": -12
64
+ })
65
+
66
+ return image
67
+
68
+ async def return_video(video):
69
+ print(video)
70
+ gr.Info("Extracting frames..")
71
+ frames = get_all_frames(video)
72
+ gr.Info("Loading frames..")
73
+ res = await engine.load_frames(frames)
74
+ id = res['u']
75
+
76
+ height, width, _ = frames[0].shape
77
+ output_file = "output_video.mp4"
78
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
79
+ video_writer = cv2.VideoWriter(output_file, fourcc, 24.0, (width, height))
80
+
81
+ gr.Info("Processing..")
82
+ async for image in engine.transform_video(id, {
83
+ "aaa": -10,
84
+ "eee": -10,
85
+ "woo": -12
86
+ }):
87
+ bgr_frame = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
88
+ video_writer.write(cv2.cvtColor(bgr_frame, cv2.COLOR_BGR2RGB))
89
+
90
+ video_writer.release()
91
+ return output_file
92
+
93
+ with gr.Blocks(title="Retorno de Imagem") as interface:
94
+ gr.Markdown("## 📼 Conversor de Vídeo para Imagem")
95
+
96
+ with gr.Row(): # Organiza os componentes em uma linha
97
+ video_input = gr.Video(label="Carregue seu vídeo")
98
+ image_output = gr.Video(label="Imagem Processada",)
99
+
100
+ submit_btn = gr.Button("🔁 Processar", variant="primary") # Estilo primário
101
+
102
+ submit_btn.click(
103
+ fn=return_video, # Sua função de processamento
104
+ inputs=video_input,
105
+ outputs=image_output,
106
+ )
107
+
108
+ interface.launch(share=True)
109
+
110
+
111
+ if __name__ == "__main__":
112
+ asyncio.run(setup())'''
113
 
114
+ import sys
115
+ import asyncio
116
+ from aiohttp import web, WSMsgType
117
+ import json
118
+ from json import JSONEncoder
119
+ import numpy as np
120
+ import uuid
121
+ import logging
122
+ import os
123
+ import signal
124
+ from typing import Dict, Any, List, Optional
125
+ import base64
126
+ import io
127
+ from PIL import Image
128
+ import gradio as gr
129
+ import cv2
130
+
131
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
132
+ logger = logging.getLogger(__name__)
133
+
134
+ def SIGSEGV_signal_arises(signalNum, stack):
135
+ logger.critical(f"{signalNum} : SIGSEGV arises")
136
+ logger.critical(f"Stack trace: {stack}")
137
+
138
+ signal.signal(signal.SIGSEGV, SIGSEGV_signal_arises)
139
+
140
+ from loader import initialize_models
141
+ from engine import Engine, base64_data_uri_to_PIL_Image
142
+ from pathlib import Path
143
+
144
+ import cv2
145
+
146
+ # Global constants
147
+ DATA_ROOT = os.environ.get('DATA_ROOT', '/tmp/data')
148
+ MODELS_DIR = os.path.join(DATA_ROOT, "models")
149
+
150
+ async def setup():
151
+ live_portrait = await initialize_models()
152
+ engine = Engine(live_portrait=live_portrait)
153
 
154
+ async def return_video(video):
155
+ gr.Info("Processing video..")
156
+ output = engine.process_video(video, {
157
+ "aaa": -10,
158
+ "eee": -10,
159
+ "woo": -12
160
+ })
161
 
162
+ return output_file
 
163
 
164
+ interface = gr.Interface(
165
+ fn=return_video, # Your function to process video
166
+ inputs=gr.Video(label="Carregue seu vídeo"),
167
+ outputs=gr.Video(label="Imagem Processada"),
168
+ title="Retorno de Imagem",
169
+ description="📼 Conversor de Vídeo para Imagem"
170
+ )
171
 
172
+ interface.launch(share=True)
173
 
 
 
 
 
 
174
 
175
  if __name__ == "__main__":
176
+ asyncio.run(setup())