MarioPrzBasto commited on
Commit
e5c9354
·
verified ·
1 Parent(s): c2df641

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +51 -33
main.py CHANGED
@@ -76,7 +76,8 @@ def load_image(source, ffmpeg_path='ffmpeg', frame_time=1):
76
  Image.MAX_IMAGE_PIXELS = None
77
 
78
  def extract_frame_from_video(video_path_or_url, time_sec):
79
- print(f"A extrair video com url {video_path_or_url}")
 
80
  with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as temp_frame:
81
  frame_path = temp_frame.name
82
 
@@ -89,47 +90,64 @@ def load_image(source, ffmpeg_path='ffmpeg', frame_time=1):
89
  "-y",
90
  frame_path
91
  ]
92
- subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
 
 
 
 
 
 
 
 
93
 
94
  if not os.path.exists(frame_path):
95
- raise ValueError("Failed to extract frame from video.")
 
96
 
97
  frame = cv2.imread(frame_path, cv2.IMREAD_GRAYSCALE)
98
  os.remove(frame_path)
99
 
100
- print(f"Video com url {video_path_or_url} extraido")
101
- return frame
102
-
103
- if source.startswith('http'):
104
- mime_type, _ = mimetypes.guess_type(source)
105
- if mime_type and mime_type.startswith('video'):
106
- return extract_frame_from_video(source, frame_time)
107
 
108
- # Assume imagem
109
- response = requests.get(source)
110
- img = np.asarray(bytearray(response.content), dtype=np.uint8)
111
- img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
112
- return img
113
 
114
- else:
115
- try:
116
- img_bytes = base64.b64decode(source)
117
- mime_type = mimetypes.guess_type("data")[0] # fallback
118
-
119
- # Tenta abrir como imagem
120
- img = Image.open(BytesIO(img_bytes))
121
- img = np.array(img)
122
- img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
 
 
 
123
  return img
124
- except Exception:
125
- # Se falhar, assumimos que é vídeo em base64 e extraímos frame
126
- with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
127
- temp_video.write(base64.b64decode(source))
128
- temp_video_path = temp_video.name
129
-
130
- frame = extract_frame_from_video(temp_video_path, frame_time)
131
- os.remove(temp_video_path)
132
- return frame
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  @app.post("/save")
135
  async def save(image_data: RequestModel):
 
76
  Image.MAX_IMAGE_PIXELS = None
77
 
78
  def extract_frame_from_video(video_path_or_url, time_sec):
79
+ print(f"[INFO] A extrair frame do vídeo: {video_path_or_url} no segundo {time_sec}")
80
+
81
  with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as temp_frame:
82
  frame_path = temp_frame.name
83
 
 
90
  "-y",
91
  frame_path
92
  ]
93
+
94
+ print(f"[DEBUG] Comando ffmpeg: {' '.join(command)}")
95
+
96
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
97
+
98
+ if result.returncode != 0:
99
+ print(f"[ERRO] ffmpeg falhou com código {result.returncode}")
100
+ print(f"[ERRO] stderr: {result.stderr.decode('utf-8')}")
101
+ raise RuntimeError("Erro ao extrair frame com ffmpeg.")
102
 
103
  if not os.path.exists(frame_path):
104
+ print("[ERRO] Frame não criado. Verifica se o caminho do vídeo está correto e acessível.")
105
+ raise ValueError("Frame não encontrado após execução do ffmpeg.")
106
 
107
  frame = cv2.imread(frame_path, cv2.IMREAD_GRAYSCALE)
108
  os.remove(frame_path)
109
 
110
+ if frame is None:
111
+ print("[ERRO] Falha ao ler frame extraído com OpenCV.")
112
+ raise ValueError("Erro ao carregar frame extraído.")
 
 
 
 
113
 
114
+ print(f"[SUCESSO] Frame extraído com sucesso de {video_path_or_url}")
115
+ return frame
 
 
 
116
 
117
+ try:
118
+ if source.startswith('http'):
119
+ mime_type, _ = mimetypes.guess_type(source)
120
+ print(f"[INFO] Mime_type de {source} é {mime_type}")
121
+
122
+ if mime_type and mime_type.startswith('video'):
123
+ return extract_frame_from_video(source, frame_time)
124
+
125
+ print(f"[INFO] A carregar imagem de URL: {source}")
126
+ response = requests.get(source)
127
+ img = np.asarray(bytearray(response.content), dtype=np.uint8)
128
+ img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
129
  return img
130
+
131
+ else:
132
+ print("[INFO] A tentar carregar base64 como imagem.")
133
+ try:
134
+ img_bytes = base64.b64decode(source)
135
+ img = Image.open(BytesIO(img_bytes))
136
+ img = np.array(img)
137
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
138
+ return img
139
+ except Exception:
140
+ print("[INFO] Base64 não é imagem, a assumir que é vídeo.")
141
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
142
+ temp_video.write(base64.b64decode(source))
143
+ temp_video_path = temp_video.name
144
+
145
+ frame = extract_frame_from_video(temp_video_path, frame_time)
146
+ os.remove(temp_video_path)
147
+ return frame
148
+ except Exception as e:
149
+ print(f"[ERRO] Falha ao carregar imagem: {e}")
150
+ return None
151
 
152
  @app.post("/save")
153
  async def save(image_data: RequestModel):