Carlexx commited on
Commit
ff301dc
·
verified ·
1 Parent(s): ae9ff21

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -22
app.py CHANGED
@@ -3,7 +3,7 @@ import cv2
3
  import numpy as np
4
  from skimage.metrics import structural_similarity as ssim
5
  import matplotlib.pyplot as plt
6
- from PIL import Image
7
  import imagehash
8
  import os
9
  import math
@@ -23,6 +23,9 @@ def analisar_video(video_path, progress=gr.Progress()):
23
  cap = cv2.VideoCapture(video_path)
24
  frames = []
25
  fps = cap.get(cv2.CAP_PROP_FPS)
 
 
 
26
  while True:
27
  ret, frame = cap.read()
28
  if not ret:
@@ -42,12 +45,10 @@ def analisar_video(video_path, progress=gr.Progress()):
42
  frame_atual = frames[i]
43
  proximo_frame = frames[i+1]
44
 
45
- # Converte para cinza para SSIM
46
  gray1 = cv2.cvtColor(frame_atual, cv2.COLOR_RGB2GRAY)
47
  gray2 = cv2.cvtColor(proximo_frame, cv2.COLOR_RGB2GRAY)
48
  ssim_val, _ = ssim(gray1, gray2, full=True)
49
 
50
- # Converte para PIL para pHash
51
  pil_img1 = Image.fromarray(frame_atual)
52
  pil_img2 = Image.fromarray(proximo_frame)
53
  phash_dist = imagehash.phash(pil_img1) - imagehash.phash(pil_img2)
@@ -66,14 +67,12 @@ def analisar_video(video_path, progress=gr.Progress()):
66
  return grafico_path, timeline_path
67
 
68
  def gerar_grafico_analise(ssim_scores, phash_distances, num_frames, fps):
69
- """Gera e salva um gráfico com as métricas de análise."""
70
  x_axis_frames = range(num_frames - 1)
71
  x_axis_time = [i / fps for i in x_axis_frames]
72
 
73
  fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 10), sharex=True)
74
  fig.suptitle('Análise Quantitativa da Coerência do Vídeo', fontsize=16)
75
 
76
- # --- Gráfico 1: SSIM ---
77
  ax1.plot(x_axis_time, ssim_scores, color='tab:blue', lw=2)
78
  ax1.set_ylabel('Índice SSIM (1.0 = Perfeito)')
79
  ax1.set_title('Métrica 1: Fidelidade do Eco e Continuidade da Cena')
@@ -82,7 +81,6 @@ def gerar_grafico_analise(ssim_scores, phash_distances, num_frames, fps):
82
  ax1.axhline(y=0.9, color='green', linestyle='--', label='Limiar de Alta Fidelidade (0.9)')
83
  ax1.legend()
84
 
85
- # --- Gráfico 2: pHash ---
86
  ax2.plot(x_axis_time, phash_distances, color='tab:red', lw=2)
87
  ax2.set_ylabel('Distância pHash (0 = Idêntico)')
88
  ax2.set_title('Métrica 2: Detecção de Transições Semânticas e Cortes')
@@ -96,30 +94,25 @@ def gerar_grafico_analise(ssim_scores, phash_distances, num_frames, fps):
96
 
97
  grafico_path = 'analise_fidelidade.png'
98
  plt.savefig(grafico_path)
99
- plt.close() # Libera memória
100
  return grafico_path
101
 
102
  def gerar_timeline_visual(frames, num_frames, fps):
103
- """Cria uma única imagem com miniaturas de frames em intervalos regulares."""
104
  intervalo_frames = 8
105
  indices_selecionados = list(range(0, num_frames, intervalo_frames))
106
 
107
  thumbnails = []
108
  for i in indices_selecionados:
109
  frame = Image.fromarray(frames[i])
110
- # Redimensiona mantendo a proporção
111
  aspect_ratio = frame.width / frame.height
112
  new_width = int(THUMBNAIL_HEIGHT * aspect_ratio)
113
  thumbnail = frame.resize((new_width, THUMBNAIL_HEIGHT), Image.Resampling.LANCZOS)
114
  thumbnails.append(thumbnail)
115
 
116
- # Calcula o tamanho da imagem final
117
  total_width = sum(t.width for t in thumbnails)
118
  max_height = THUMBNAIL_HEIGHT
119
 
120
- # Cria a imagem da timeline
121
- timeline_img = Image.new('RGB', (total_width, max_height + 40), (255, 255, 255))
122
- from PIL import ImageDraw, ImageFont
123
  draw = ImageDraw.Draw(timeline_img)
124
  try:
125
  font = ImageFont.truetype("DejaVuSans.ttf", 15)
@@ -129,10 +122,9 @@ def gerar_timeline_visual(frames, num_frames, fps):
129
  current_x = 0
130
  for i, thumb in enumerate(thumbnails):
131
  timeline_img.paste(thumb, (current_x, 0))
132
- # Adiciona o timestamp
133
  frame_idx = indices_selecionados[i]
134
  timestamp = frame_idx / fps
135
- draw.text((current_x + 5, max_height + 5), f"{timestamp:.1f}s", fill=(0,0,0), font=font)
136
  current_x += thumb.width
137
 
138
  timeline_path = 'timeline_visual.png'
@@ -167,14 +159,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Analisador de Coerência ADUC-SDR"
167
  inputs=[video_input],
168
  outputs=[plot_output, timeline_output]
169
  )
170
-
171
- gr.Examples(
172
- [["https://huggingface.co/spaces/carlex22/aduc-sdr/resolve/main/video.mp4"]],
173
- inputs=[video_input],
174
- )
175
 
 
176
 
177
  if __name__ == "__main__":
178
- # Para rodar localmente com GPU, você pode precisar configurar o PyTorch.
179
- # No HF Spaces, a GPU é gerenciada pelo ambiente.
180
  demo.queue().launch(share=True)
 
3
  import numpy as np
4
  from skimage.metrics import structural_similarity as ssim
5
  import matplotlib.pyplot as plt
6
+ from PIL import Image, ImageDraw, ImageFont
7
  import imagehash
8
  import os
9
  import math
 
23
  cap = cv2.VideoCapture(video_path)
24
  frames = []
25
  fps = cap.get(cv2.CAP_PROP_FPS)
26
+ if fps == 0:
27
+ fps = 30 # Define um padrão caso não consiga ler o FPS
28
+
29
  while True:
30
  ret, frame = cap.read()
31
  if not ret:
 
45
  frame_atual = frames[i]
46
  proximo_frame = frames[i+1]
47
 
 
48
  gray1 = cv2.cvtColor(frame_atual, cv2.COLOR_RGB2GRAY)
49
  gray2 = cv2.cvtColor(proximo_frame, cv2.COLOR_RGB2GRAY)
50
  ssim_val, _ = ssim(gray1, gray2, full=True)
51
 
 
52
  pil_img1 = Image.fromarray(frame_atual)
53
  pil_img2 = Image.fromarray(proximo_frame)
54
  phash_dist = imagehash.phash(pil_img1) - imagehash.phash(pil_img2)
 
67
  return grafico_path, timeline_path
68
 
69
  def gerar_grafico_analise(ssim_scores, phash_distances, num_frames, fps):
 
70
  x_axis_frames = range(num_frames - 1)
71
  x_axis_time = [i / fps for i in x_axis_frames]
72
 
73
  fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 10), sharex=True)
74
  fig.suptitle('Análise Quantitativa da Coerência do Vídeo', fontsize=16)
75
 
 
76
  ax1.plot(x_axis_time, ssim_scores, color='tab:blue', lw=2)
77
  ax1.set_ylabel('Índice SSIM (1.0 = Perfeito)')
78
  ax1.set_title('Métrica 1: Fidelidade do Eco e Continuidade da Cena')
 
81
  ax1.axhline(y=0.9, color='green', linestyle='--', label='Limiar de Alta Fidelidade (0.9)')
82
  ax1.legend()
83
 
 
84
  ax2.plot(x_axis_time, phash_distances, color='tab:red', lw=2)
85
  ax2.set_ylabel('Distância pHash (0 = Idêntico)')
86
  ax2.set_title('Métrica 2: Detecção de Transições Semânticas e Cortes')
 
94
 
95
  grafico_path = 'analise_fidelidade.png'
96
  plt.savefig(grafico_path)
97
+ plt.close()
98
  return grafico_path
99
 
100
  def gerar_timeline_visual(frames, num_frames, fps):
 
101
  intervalo_frames = 8
102
  indices_selecionados = list(range(0, num_frames, intervalo_frames))
103
 
104
  thumbnails = []
105
  for i in indices_selecionados:
106
  frame = Image.fromarray(frames[i])
 
107
  aspect_ratio = frame.width / frame.height
108
  new_width = int(THUMBNAIL_HEIGHT * aspect_ratio)
109
  thumbnail = frame.resize((new_width, THUMBNAIL_HEIGHT), Image.Resampling.LANCZOS)
110
  thumbnails.append(thumbnail)
111
 
 
112
  total_width = sum(t.width for t in thumbnails)
113
  max_height = THUMBNAIL_HEIGHT
114
 
115
+ timeline_img = Image.new('RGB', (total_width, max_height + 40), (20, 20, 20)) # Fundo escuro
 
 
116
  draw = ImageDraw.Draw(timeline_img)
117
  try:
118
  font = ImageFont.truetype("DejaVuSans.ttf", 15)
 
122
  current_x = 0
123
  for i, thumb in enumerate(thumbnails):
124
  timeline_img.paste(thumb, (current_x, 0))
 
125
  frame_idx = indices_selecionados[i]
126
  timestamp = frame_idx / fps
127
+ draw.text((current_x + 5, max_height + 5), f"{timestamp:.1f}s", fill=(255,255,255), font=font) # Texto branco
128
  current_x += thumb.width
129
 
130
  timeline_path = 'timeline_visual.png'
 
159
  inputs=[video_input],
160
  outputs=[plot_output, timeline_output]
161
  )
 
 
 
 
 
162
 
163
+ # O bloco gr.Examples foi removido daqui.
164
 
165
  if __name__ == "__main__":
 
 
166
  demo.queue().launch(share=True)