Spaces:
Sleeping
Sleeping
| # app.py - VERSÃO FINAL, COMPLETA E CORRIGIDA | |
| import os | |
| import cv2 | |
| import numpy as np | |
| import base64 | |
| import tempfile | |
| import zipfile | |
| import uuid | |
| from flask import Flask, request, jsonify, render_template, send_from_directory | |
| from werkzeug.utils import secure_filename | |
| # --- CONFIGURAÇÃO DA APLICAÇÃO --- | |
| app = Flask(__name__) | |
| UPLOAD_FOLDER = tempfile.gettempdir() | |
| app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER | |
| app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB | |
| # --- FUNÇÕES DE PROCESSAMENTO DE IMAGEM --- | |
| def process_image(image_path, options): | |
| """ | |
| Função principal que orquestra o pipeline de processamento de imagem. | |
| Versão corrigida para imagens com pistas brancas sobre fundo preto. | |
| """ | |
| img = cv2.imread(image_path) | |
| if img is None: raise ValueError("Não foi possível ler a imagem.") | |
| # 1. Converter para escala de cinza | |
| gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
| # 2. Pré-processamento (opcional, mas útil) | |
| if options.get('enhance_contrast'): | |
| clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) | |
| gray = clahe.apply(gray) | |
| if options.get('remove_noise'): | |
| gray = cv2.medianBlur(gray, 3) | |
| # 3. Binarização da imagem (CORRIGIDO) | |
| # Usamos THRESH_BINARY: pixels claros (acima do threshold) ficam brancos. | |
| _, binary_img = cv2.threshold( | |
| gray, options.get('threshold'), 255, cv2.THRESH_BINARY | |
| ) | |
| # 4. LIMPEZA AVANÇADA DOS CONTORNOS | |
| kernel = np.ones((2, 2), np.uint8) | |
| cleaned_img = cv2.morphologyEx(binary_img, cv2.MORPH_OPEN, kernel, iterations=2) | |
| cleaned_img = cv2.morphologyEx(cleaned_img, cv2.MORPH_CLOSE, kernel, iterations=2) | |
| # 5. Encontrar os contornos na imagem JÁ LIMPA | |
| contours, _ = cv2.findContours( | |
| cleaned_img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE | |
| ) | |
| # 6. Filtrar contornos muito pequenos | |
| min_area = options.get('min_area') | |
| filtered_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > min_area] | |
| if options.get('smooth_curves'): | |
| smoothed_contours = [cv2.approxPolyDP(cnt, 0.001 * cv2.arcLength(cnt, True), True) for cnt in filtered_contours] | |
| filtered_contours = smoothed_contours | |
| # 7. Gerar pré-visualizações (a função agora existe) | |
| previews = generate_previews(img, cleaned_img, filtered_contours) | |
| return filtered_contours, previews | |
| def generate_previews(original_img, binary_img, contours): | |
| """ | |
| Função que gera imagens em Base64 para mostrar no frontend. | |
| """ | |
| contour_preview = np.zeros_like(original_img) | |
| cv2.drawContours(contour_preview, contours, -1, (102, 126, 234), 2) | |
| def to_base64(img_array): | |
| _, buffer = cv2.imencode('.png', img_array) | |
| return base64.b64encode(buffer).decode('utf-8') | |
| return { | |
| 'original': to_base64(original_img), | |
| 'binary': to_base64(binary_img), # Mostra a imagem binária já limpa | |
| 'contours': to_base64(contour_preview) | |
| } | |
| # --- FUNÇÕES DE GERAÇÃO DE FICHEIROS --- | |
| def create_gerber_manually(contours, img_height, dpi, output_path): | |
| """ | |
| Cria um ficheiro Gerber a partir de contornos, sem bibliotecas externas. | |
| """ | |
| scale_factor = 25.4 / dpi | |
| precision = 10000 | |
| gerber_commands = ["%FSLAX44Y44*%", "%MOMM*%", "%LPD*%"] | |
| for contour in contours: | |
| gerber_commands.append("G36*") | |
| first_point = contour[0][0] | |
| x_mm = first_point[0] * scale_factor | |
| y_mm = (img_height - first_point[1]) * scale_factor | |
| gerber_commands.append(f"X{int(x_mm * precision)}Y{int(y_mm * precision)}D02*") | |
| for point in contour[1:]: | |
| p = point[0] | |
| x_mm = p[0] * scale_factor | |
| y_mm = (img_height - p[1]) * scale_factor | |
| gerber_commands.append(f"X{int(x_mm * precision)}Y{int(y_mm * precision)}D01*") | |
| gerber_commands.append(f"X{int(x_mm * precision)}Y{int(y_mm * precision)}D01*") | |
| gerber_commands.append("G37*") | |
| gerber_commands.append("M02*") | |
| with open(output_path, 'w') as f: | |
| f.write("\n".join(gerber_commands) + "\n") | |
| def create_drill_file(contours, img_height, dpi, output_path): | |
| drill_holes = [] | |
| for cnt in contours: | |
| area = cv2.contourArea(cnt) | |
| perimeter = cv2.arcLength(cnt, True) | |
| if perimeter == 0: continue | |
| circularity = 4 * np.pi * (area / (perimeter * perimeter)) | |
| if 0.8 < circularity < 1.2: | |
| (x, y), radius = cv2.minEnclosingCircle(cnt) | |
| x_inch, y_inch = x / dpi, (img_height - y) / dpi | |
| diameter_inch = (radius * 2) / dpi | |
| drill_holes.append({'x': x_inch, 'y': y_inch, 'd': diameter_inch}) | |
| if not drill_holes: return False | |
| with open(output_path, 'w') as f: | |
| f.write("M48\nINCH,LZ\nFMAT,2\n") | |
| tools = {} | |
| for hole in drill_holes: | |
| d_str = f"{hole['d']:.4f}" | |
| if d_str not in tools: tools[d_str] = [] | |
| tools[d_str].append(hole) | |
| tool_id = 1 | |
| for d_str, _ in tools.items(): | |
| f.write(f"T{tool_id}C{d_str}\n"); tool_id += 1 | |
| f.write("%\n") | |
| tool_id = 1 | |
| for _, holes in tools.items(): | |
| f.write(f"T{tool_id}\n") | |
| for hole in holes: f.write(f"X{hole['x']:.4f}Y{hole['y']:.4f}\n") | |
| tool_id += 1 | |
| f.write("M30\n") | |
| return True | |
| def create_svg(contours, width, height, dpi, output_path): | |
| width_mm, height_mm = width / dpi * 25.4, height / dpi * 25.4 | |
| svg = f'<svg width="{width_mm}mm" height="{height_mm}mm" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">\n' | |
| svg += '<style>.pcb-trace { fill: #2c9a55; stroke: #2c9a55; stroke-width: 0.5; }</style>\n' | |
| svg += f'<g transform="translate(0, {height}) scale(1, -1)">\n' | |
| for contour in contours: | |
| points = " ".join([f"{p[0][0]},{p[0][1]}" for p in contour]) | |
| svg += f' <polygon class="pcb-trace" points="{points}" />\n' | |
| svg += '</g>\n</svg>' | |
| with open(output_path, "w") as f: f.write(svg) | |
| # --- ROTAS DA API FLASK --- | |
| def index(): return render_template('index.html') | |
| def process_route(): | |
| if 'image' not in request.files: return jsonify({'success': False, 'error': 'Nenhum ficheiro'}), 400 | |
| file = request.files['image'] | |
| if file.filename == '': return jsonify({'success': False, 'error': 'Nenhum ficheiro'}), 400 | |
| DPI = 600 | |
| try: | |
| options = {'threshold': int(request.form.get('threshold', 127)), 'min_area': int(request.form.get('minArea', 100)), 'remove_noise': request.form.get('removeNoise') == 'true', 'enhance_contrast': request.form.get('enhanceContrast') == 'true', 'smooth_curves': request.form.get('smoothCurves') == 'true', 'generate_drill': request.form.get('generateDrill') == 'true'} | |
| filename = secure_filename(file.filename) | |
| temp_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) | |
| file.save(temp_path) | |
| # Chamada ao processamento | |
| contours, previews = process_image(temp_path, options) | |
| session_id = str(uuid.uuid4()) | |
| filenames = {'gbr': f"{session_id}.gbr", 'svg': f"{session_id}.svg", 'drl': f"{session_id}.drl", 'zip': f"{session_id}.zip"} | |
| paths = {k: os.path.join(app.config['UPLOAD_FOLDER'], v) for k, v in filenames.items()} | |
| img_h, img_w = cv2.imread(temp_path).shape[:2] | |
| create_gerber_manually(contours, img_h, DPI, paths['gbr']) | |
| create_svg(contours, img_w, img_h, DPI, paths['svg']) | |
| with open(paths['svg'], 'rb') as f: previews['svg'] = base64.b64encode(f.read()).decode('utf-8') | |
| drill_gen = create_drill_file(contours, img_h, DPI, paths['drl']) if options['generate_drill'] else False | |
| with zipfile.ZipFile(paths['zip'], 'w') as zf: | |
| zf.write(paths['gbr'], os.path.basename(paths['gbr'])) | |
| zf.write(paths['svg'], os.path.basename(paths['svg'])) | |
| if drill_gen: zf.write(paths['drl'], os.path.basename(paths['drl'])) | |
| response_data = {'success': True, 'data': {'previews': previews, 'files': {'zip': filenames['zip'], 'gerber': filenames['gbr'], 'svg': filenames['svg'], 'drill': filenames['drl'] if drill_gen else None}}} | |
| os.remove(temp_path) | |
| return jsonify(response_data) | |
| except Exception as e: | |
| app.logger.error(f"Erro no processamento: {e}", exc_info=True) | |
| return jsonify({'success': False, 'error': str(e)}), 500 | |
| def download_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True) | |
| if __name__ == '__main__': | |
| app.run(debug=True, port=5000) |