cngsm commited on
Commit
2908964
·
verified ·
1 Parent(s): fcee092

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -45
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  import json
 
3
  from datetime import datetime
4
  from utils.video_processor import VideoProcessor
5
  from utils.mediapipe_utils import MediaPipeProcessor
@@ -11,45 +12,58 @@ class LibrasProcessingPipeline:
11
  self.setup_directories()
12
 
13
  def setup_directories(self):
14
- """Cria os diretórios necessários"""
15
- os.makedirs(self.config['input_dir'], exist_ok=True)
16
- os.makedirs(self.config['normalized_dir'], exist_ok=True)
17
- os.makedirs(self.config['keypoints_dir'], exist_ok=True)
18
- os.makedirs(self.config['huggingface_dir'], exist_ok=True)
 
 
 
 
 
 
19
 
20
  def run_pipeline(self, video_filename):
21
  """Executa o pipeline completo"""
22
  print(f"Iniciando processamento do vídeo: {video_filename}")
23
 
24
- # 1. Normalização do vídeo
25
- print("1. Normalizando vídeo...")
26
- normalized_path = self.normalize_video(video_filename)
27
-
28
- # 2. Extração de keypoints com MediaPipe
29
- print("2. Extraindo keypoints...")
30
- keypoints_data = self.extract_keypoints(normalized_path)
31
-
32
- # 3. Salvar JSON com keypoints
33
- print("3. Salvando keypoints...")
34
- json_path = self.save_keypoints(keypoints_data, video_filename)
35
-
36
- # 4. Preparar para Hugging Face
37
- print("4. Preparando para Hugging Face...")
38
- hf_ready_path = self.prepare_for_huggingface(
39
- normalized_path, json_path, video_filename
40
- )
41
-
42
- # 5. Upload para Hugging Face (opcional)
43
- if self.config.get('upload_to_hf', False):
44
- print("5. Upload para Hugging Face...")
45
- self.upload_to_huggingface(hf_ready_path)
46
-
47
- print("Pipeline concluído com sucesso!")
48
- return {
49
- 'normalized_video': normalized_path,
50
- 'keypoints_json': json_path,
51
- 'hf_ready': hf_ready_path
52
- }
 
 
 
 
 
 
 
53
 
54
  def normalize_video(self, video_filename):
55
  """Normaliza o vídeo usando OpenCV/FFmpeg"""
@@ -90,6 +104,7 @@ class LibrasProcessingPipeline:
90
  with open(output_path, 'w', encoding='utf-8') as f:
91
  json.dump(serializable_data, f, indent=2, ensure_ascii=False)
92
 
 
93
  return output_path
94
 
95
  def prepare_for_huggingface(self, video_path, json_path, original_filename):
@@ -103,26 +118,29 @@ class LibrasProcessingPipeline:
103
  if os.path.exists(video_path):
104
  import shutil
105
  shutil.copy2(video_path, video_dest)
 
106
 
107
  # Copiar JSON de keypoints
108
  json_dest = os.path.join(hf_dir, f"{base_name}_keypoints.json")
109
  if os.path.exists(json_path):
110
  import shutil
111
  shutil.copy2(json_path, json_dest)
 
112
 
113
  # Criar metadata
114
  metadata = {
115
  'processing_date': datetime.now().isoformat(),
116
  'original_video': original_filename,
117
  'keypoints_format': 'MediaPipe Holistic',
118
- 'frame_count': len(self.load_json(json_path)),
119
- 'video_resolution': self.get_video_info(video_path)
120
  }
121
 
122
  metadata_path = os.path.join(hf_dir, 'metadata.json')
123
  with open(metadata_path, 'w', encoding='utf-8') as f:
124
  json.dump(metadata, f, indent=2, ensure_ascii=False)
125
 
 
126
  return hf_dir
127
 
128
  def upload_to_huggingface(self, directory_path):
@@ -132,6 +150,8 @@ class LibrasProcessingPipeline:
132
 
133
  def load_json(self, json_path):
134
  """Carrega arquivo JSON"""
 
 
135
  with open(json_path, 'r', encoding='utf-8') as f:
136
  return json.load(f)
137
 
@@ -169,19 +189,35 @@ config = {
169
 
170
  'huggingface': {
171
  'repo_id': 'your-username/your-repo-name',
172
- 'token': 'your-hf-token', # Opcional: só se quiser upload automático
173
- 'upload_to_hf': False # Mudar para True para habilitar upload
174
  }
175
  }
176
 
177
  if __name__ == "__main__":
178
- # Exemplo de uso
179
  pipeline = LibrasProcessingPipeline(config)
180
 
181
- # Processar um vídeo específico
182
- try:
183
- result = pipeline.run_pipeline("video_libras.mp4")
184
- print(f"Resultados salvos em: {result}")
185
 
186
- except Exception as e:
187
- print(f"Erro no processamento: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import json
3
+ import time
4
  from datetime import datetime
5
  from utils.video_processor import VideoProcessor
6
  from utils.mediapipe_utils import MediaPipeProcessor
 
12
  self.setup_directories()
13
 
14
  def setup_directories(self):
15
+ """Cria os diretórios necessários automaticamente"""
16
+ directories = [
17
+ self.config['input_dir'],
18
+ self.config['normalized_dir'],
19
+ self.config['keypoints_dir'],
20
+ self.config['huggingface_dir']
21
+ ]
22
+
23
+ for directory in directories:
24
+ os.makedirs(directory, exist_ok=True)
25
+ print(f"Diretório criado/verificado: {directory}")
26
 
27
  def run_pipeline(self, video_filename):
28
  """Executa o pipeline completo"""
29
  print(f"Iniciando processamento do vídeo: {video_filename}")
30
 
31
+ try:
32
+ # 1. Normalização do vídeo
33
+ print("1. Normalizando vídeo...")
34
+ normalized_path = self.normalize_video(video_filename)
35
+
36
+ # 2. Extração de keypoints com MediaPipe
37
+ print("2. Extraindo keypoints...")
38
+ keypoints_data = self.extract_keypoints(normalized_path)
39
+
40
+ # 3. Salvar JSON com keypoints
41
+ print("3. Salvando keypoints...")
42
+ json_path = self.save_keypoints(keypoints_data, video_filename)
43
+
44
+ # 4. Preparar para Hugging Face
45
+ print("4. Preparando para Hugging Face...")
46
+ hf_ready_path = self.prepare_for_huggingface(
47
+ normalized_path, json_path, video_filename
48
+ )
49
+
50
+ # 5. Upload para Hugging Face (opcional)
51
+ if self.config.get('upload_to_hf', False):
52
+ print("5. Upload para Hugging Face...")
53
+ self.upload_to_huggingface(hf_ready_path)
54
+
55
+ print("Pipeline concluído com sucesso!")
56
+ return {
57
+ 'normalized_video': normalized_path,
58
+ 'keypoints_json': json_path,
59
+ 'hf_ready': hf_ready_path
60
+ }
61
+
62
+ except Exception as e:
63
+ print(f"Erro no pipeline: {e}")
64
+ import traceback
65
+ traceback.print_exc()
66
+ return None
67
 
68
  def normalize_video(self, video_filename):
69
  """Normaliza o vídeo usando OpenCV/FFmpeg"""
 
104
  with open(output_path, 'w', encoding='utf-8') as f:
105
  json.dump(serializable_data, f, indent=2, ensure_ascii=False)
106
 
107
+ print(f"Keypoints salvos em: {output_path}")
108
  return output_path
109
 
110
  def prepare_for_huggingface(self, video_path, json_path, original_filename):
 
118
  if os.path.exists(video_path):
119
  import shutil
120
  shutil.copy2(video_path, video_dest)
121
+ print(f"Vídeo copiado para: {video_dest}")
122
 
123
  # Copiar JSON de keypoints
124
  json_dest = os.path.join(hf_dir, f"{base_name}_keypoints.json")
125
  if os.path.exists(json_path):
126
  import shutil
127
  shutil.copy2(json_path, json_dest)
128
+ print(f"JSON copiado para: {json_dest}")
129
 
130
  # Criar metadata
131
  metadata = {
132
  'processing_date': datetime.now().isoformat(),
133
  'original_video': original_filename,
134
  'keypoints_format': 'MediaPipe Holistic',
135
+ 'frame_count': len(self.load_json(json_path)) if os.path.exists(json_path) else 0,
136
+ 'video_resolution': self.get_video_info(video_path) if os.path.exists(video_path) else {}
137
  }
138
 
139
  metadata_path = os.path.join(hf_dir, 'metadata.json')
140
  with open(metadata_path, 'w', encoding='utf-8') as f:
141
  json.dump(metadata, f, indent=2, ensure_ascii=False)
142
 
143
+ print(f"Metadata criado em: {metadata_path}")
144
  return hf_dir
145
 
146
  def upload_to_huggingface(self, directory_path):
 
150
 
151
  def load_json(self, json_path):
152
  """Carrega arquivo JSON"""
153
+ if not os.path.exists(json_path):
154
+ return []
155
  with open(json_path, 'r', encoding='utf-8') as f:
156
  return json.load(f)
157
 
 
189
 
190
  'huggingface': {
191
  'repo_id': 'your-username/your-repo-name',
192
+ 'token': 'your-hf-token',
193
+ 'upload_to_hf': False
194
  }
195
  }
196
 
197
  if __name__ == "__main__":
198
+ # Criar diretórios automaticamente
199
  pipeline = LibrasProcessingPipeline(config)
200
 
201
+ # Verificar se existe vídeo na pasta input
202
+ input_dir = config['input_dir']
203
+ video_files = [f for f in os.listdir(input_dir) if f.endswith(('.mp4', '.avi', '.mov'))]
 
204
 
205
+ if not video_files:
206
+ print(f"Nenhum vídeo encontrado na pasta '{input_dir}'")
207
+ print("Por favor, coloque um vídeo na pasta input/")
208
+ else:
209
+ # Processar o primeiro vídeo encontrado
210
+ video_filename = video_files[0]
211
+ print(f"Processando: {video_filename}")
212
+
213
+ start_time = time.time()
214
+ result = pipeline.run_pipeline(video_filename)
215
+ end_time = time.time()
216
+
217
+ if result:
218
+ print(f"\n✅ Processamento concluído em {end_time - start_time:.2f} segundos")
219
+ print(f"📁 Resultados:")
220
+ for key, path in result.items():
221
+ print(f" {key}: {path}")
222
+ else:
223
+ print("❌ Falha no processamento")