Files changed (1) hide show
  1. captura2.py +126 -0
captura2.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importando las librerías Gradio, requests, PIL e io
2
+ import gradio as gr
3
+ import requests
4
+ from PIL import Image
5
+ from io import BytesIO
6
+ import argparse
7
+ import os
8
+ import cv2
9
+ import requests
10
+ import numpy as np
11
+ from pathlib import Path
12
+ import warnings
13
+
14
+ import torch
15
+
16
+ from groundingdino.models import build_model
17
+ from groundingdino.util.slconfig import SLConfig
18
+ from groundingdino.util.utils import clean_state_dict
19
+ from groundingdino.util.inference import annotate, load_image, predict
20
+ import groundingdino.datasets.transforms as T
21
+
22
+ from huggingface_hub import hf_hub_download
23
+
24
+ # Use this command for evaluate the GLIP-T model
25
+ config_file = "groundingdino/config/GroundingDINO_SwinT_OGC.py"
26
+ ckpt_repo_id = "ShilongLiu/GroundingDINO"
27
+ ckpt_filenmae = "groundingdino_swint_ogc.pth"
28
+
29
+ def load_model_hf(model_config_path, repo_id, filename, device='cpu'):
30
+ args = SLConfig.fromfile(model_config_path)
31
+ model = build_model(args)
32
+ args.device = device
33
+
34
+ cache_file = hf_hub_download(repo_id=repo_id, filename=filename)
35
+ checkpoint = torch.load(cache_file, map_location='cpu')
36
+ log = model.load_state_dict(clean_state_dict(checkpoint['model']), strict=False)
37
+ print("Model loaded from {} \n => {}".format(cache_file, log))
38
+ _ = model.eval()
39
+ return model
40
+
41
+ def image_transform_grounding(init_image):
42
+ transform = T.Compose([
43
+ T.RandomResize([800], max_size=1333),
44
+ T.ToTensor(),
45
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
46
+ ])
47
+ image, _ = transform(init_image, None) # 3, h, w
48
+ return init_image, image
49
+
50
+ def image_transform_grounding_for_vis(init_image):
51
+ transform = T.Compose([
52
+ T.RandomResize([800], max_size=1333),
53
+ ])
54
+ image, _ = transform(init_image, None) # 3, h, w
55
+ return image
56
+
57
+ model = load_model_hf(config_file, ckpt_repo_id, ckpt_filenmae)
58
+
59
+ def run_grounding(input_image, grounding_caption, box_threshold, text_threshold):
60
+ init_image = input_image.convert("RGB")
61
+ original_size = init_image.size
62
+
63
+ _, image_tensor = image_transform_grounding(init_image)
64
+ image_pil: Image = image_transform_grounding_for_vis(init_image)
65
+
66
+ # run grounding
67
+ boxes, logits, phrases = predict(model, image_tensor, grounding_caption, box_threshold, text_threshold, device='cpu')
68
+ annotated_frame = annotate(image_source=np.asarray(image_pil), boxes=boxes, logits=logits, phrases=phrases)
69
+ image_with_box = Image.fromarray(cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB))
70
+
71
+ return image_with_box
72
+
73
+
74
+ # Definiendo la función captura_pagina
75
+ def captura_pagina(url):
76
+ # Asignando la clave de la API y la URL
77
+ api_key = 'b77e9ec7b82e4447b93c73cf1af4a93f'
78
+ api_url = f'https://api.apiflash.com/v1/urltoimage?access_key={api_key}&url={url}'
79
+
80
+ # Haciendo una solicitud GET a la API
81
+ respuesta = requests.get(api_url, stream=True)
82
+
83
+ # Si la solicitud es exitosa, se procesa la imagen
84
+ if respuesta.status_code == 200:
85
+ image_data = b''
86
+ for chunk in respuesta.iter_content(8192):
87
+ image_data += chunk
88
+ image = Image.open(BytesIO(image_data))
89
+
90
+ # Set the fixed box_threshold and text_threshold
91
+ box_threshold = 0.38
92
+ text_threshold = 0.25
93
+ grounding_caption = "Find the webform in the picture of a web."
94
+
95
+ # Run the Grounding DINO model on the image
96
+ image_with_bb = run_grounding(image, grounding_caption, box_threshold, text_threshold)
97
+
98
+ return "¡Página web capturada con éxito!", image, image_with_bb
99
+ else:
100
+ # Si la solicitud no es exitosa, se retorna un mensaje de error
101
+ return f'Error: {respuesta.status_code}', None, None
102
+
103
+ # Definiendo la función captura_pagina_app
104
+ def captura_pagina_app():
105
+ # Creando un objeto de la clase Row de Gradio
106
+ with gr.Row():
107
+ with gr.Column():
108
+ # Agregando un cuadro de texto para ingresar la URL
109
+ textbox_url = gr.Textbox(label='URL')
110
+
111
+ # Agregando un botón para capturar la página web
112
+ btn_predecir = gr.Button(value='Predecir')
113
+ with gr.Column():
114
+ # Agregando un cuadro de texto para mostrar el estado
115
+ output_mensaje = gr.Textbox(label='Estado')
116
+
117
+ # Agregando dos imágenes para mostrar la captura de la página web
118
+ output_img1 = gr.Image()
119
+ output_img2 = gr.Image()
120
+
121
+ # Asociando la función captura_pagina con el botón
122
+ btn_predecir.click(
123
+ fn=captura_pagina,
124
+ inputs=textbox_url,
125
+ outputs=[output_mensaje, output_img1, output_img2]
126
+ )