meccatronis commited on
Commit
72cccfb
·
verified ·
1 Parent(s): 8d343ee

Upload vision_analyzer.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. vision_analyzer.py +172 -0
vision_analyzer.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Vision Analyzer para Taobao
4
+ Recebe screenshot e extrai informações de produtos usando visão computacional
5
+ """
6
+
7
+ import sys
8
+ import json
9
+ import re
10
+ import subprocess
11
+ from pathlib import Path
12
+ from datetime import datetime
13
+
14
+ # Configurações
15
+ SCREENSHOT_DIR = Path("/tmp/taobao_screenshots")
16
+ OUTPUT_FILE = Path("/tmp/taobao_products.json")
17
+
18
+ # Padrões para extração de preços e títulos
19
+ PRICE_PATTERNS = [
20
+ r'[¥¥]\s*(\d+[.,]\d+)', # ¥123.45
21
+ r'(\d{1,5})[.,](\d{2})\s*元', # 123.45元
22
+ r'RMB\s*(\d+[.,]\d+)', # RMB 123.45
23
+ r'¥(\d+)', # ¥123
24
+ ]
25
+
26
+ # Elementos visuais típicos do Taobao
27
+ TAOBAO_INDICATORS = [
28
+ '淘宝', 'Taobao', 'tmall', '天猫', '店铺', '宝贝',
29
+ '月销', '评价', '包邮', '券', '元', '¥', '¥'
30
+ ]
31
+
32
+ def take_screenshot(output_path=None):
33
+ """Tira screenshot da tela"""
34
+ if output_path is None:
35
+ output_path = SCREENSHOT_DIR / f"screen_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
36
+
37
+ SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)
38
+
39
+ # Get screen resolution
40
+ result = subprocess.run(['xrandr'], capture_output=True, text=True)
41
+ match = re.search(r'(\d+)x(\d+).*\*', result.stdout)
42
+ if match:
43
+ width, height = match.groups()
44
+ else:
45
+ width, height = "1360", "768"
46
+
47
+ subprocess.run([
48
+ "ffmpeg", "-f", "x11grab",
49
+ "-video_size", f"{width}x{height}",
50
+ "-i", ":0",
51
+ "-frames:v", "1",
52
+ "-y", str(output_path)
53
+ ], capture_output=True, timeout=10)
54
+
55
+ return output_path
56
+
57
+ class TaobaoProductExtractor:
58
+ """Extrai produtos de screenshot do Taobao"""
59
+
60
+ def __init__(self):
61
+ self.products = []
62
+
63
+ def extract_price_from_text(self, text):
64
+ """Extrai preço de texto"""
65
+ for pattern in PRICE_PATTERNS:
66
+ match = re.search(pattern, text)
67
+ if match:
68
+ try:
69
+ price_str = match.group(1) if match.lastindex >= 1 else match.group(0)
70
+ price_str = price_str.replace(',', '.').replace('¥', '').replace('¥', '').replace('RMB', '').strip()
71
+ return float(price_str)
72
+ except:
73
+ continue
74
+ return None
75
+
76
+ def is_taobao_page(self, text):
77
+ """Verifica se é página do Taobao"""
78
+ return any(indicator in text for indicator in TAOBAO_INDICATORS)
79
+
80
+ def parse_products_from_text(self, text_lines):
81
+ """Parse produtos de linhas de texto"""
82
+ products = []
83
+
84
+ for i, line in enumerate(text_lines):
85
+ line = line.strip()
86
+
87
+ # Procura preço
88
+ price = self.extract_price_from_text(line)
89
+ if price:
90
+ # Linhas anteriores podem ser o título
91
+ title_lines = []
92
+ for j in range(max(0, i-3), i):
93
+ prev_line = text_lines[j].strip()
94
+ if prev_line and len(prev_line) > 5:
95
+ # Não é um preço nem indicador de UI
96
+ if not self.extract_price_from_text(prev_line) and len(prev_line) < 80:
97
+ title_lines.append(prev_line)
98
+
99
+ title = ' '.join(title_lines) if title_lines else f"Produto {len(products)+1}"
100
+
101
+ products.append({
102
+ 'title': title,
103
+ 'price': price,
104
+ 'raw_line': line
105
+ })
106
+
107
+ return products
108
+
109
+ def analyze_with_vision(self, image_path):
110
+ """Analisa imagem usando visão (placeholder para API de visão)"""
111
+ print(f"🔍 Analisando: {image_path}")
112
+ print("💡 Esta imagem pode ser interpretada pela API de visão")
113
+ print(f" Caminho: {image_path}")
114
+
115
+ # Retorna instrução para uso
116
+ return {
117
+ 'image_path': str(image_path),
118
+ 'needs_vision_api': True,
119
+ 'instruction': 'Use GPT-4V ou Claude Vision para extrair produtos desta imagem'
120
+ }
121
+
122
+ def analyze_screenshot(image_path):
123
+ """Analisa screenshot e extrai produtos"""
124
+ extractor = TaobaoProductExtractor()
125
+
126
+ # Simula análise - em produção usaria OCR real ou Vision API
127
+ result = extractor.analyze_with_vision(image_path)
128
+
129
+ return result
130
+
131
+ def main():
132
+ """Fluxo principal"""
133
+ import argparse
134
+
135
+ parser = argparse.ArgumentParser(description='Analyze Taobao screenshots')
136
+ parser.add_argument('--screenshot', '-s', help='Path to screenshot file')
137
+ parser.add_argument('--take', '-t', action='store_true', help='Take a new screenshot')
138
+ parser.add_argument('--output', '-o', default=str(OUTPUT_FILE), help='Output JSON file')
139
+
140
+ args = parser.parse_args()
141
+
142
+ print("=" * 60)
143
+ print(" TAOBAO VISION ANALYZER")
144
+ print("=" * 60)
145
+
146
+ if args.take:
147
+ print("\n📸 Tirando screenshot...")
148
+ img_path = take_screenshot()
149
+ print(f"✅ Screenshot salvo: {img_path}")
150
+
151
+ result = analyze_screenshot(img_path)
152
+
153
+ with open(args.output, 'w') as f:
154
+ json.dump(result, f, indent=2, ensure_ascii=False)
155
+
156
+ print(f"📄 Resultado salvo: {args.output}")
157
+
158
+ elif args.screenshot:
159
+ result = analyze_screenshot(args.screenshot)
160
+
161
+ with open(args.output, 'w') as f:
162
+ json.dump(result, f, indent=2, ensure_ascii=False)
163
+
164
+ print(f"📄 Resultado salvo: {args.output}")
165
+
166
+ else:
167
+ print("\nUso:")
168
+ print(" python vision_analyzer.py --take # Tira screenshot e analisa")
169
+ print(" python vision_analyzer.py -s /path/to/img.png # Analiza imagem existente")
170
+
171
+ if __name__ == "__main__":
172
+ main()