Luis-Filipe commited on
Commit
108331c
·
verified ·
1 Parent(s): 0e74cbf

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile.txt +25 -0
  2. README.md +10 -11
  3. app.py +201 -0
  4. requirements.txt +6 -0
Dockerfile.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Usa uma imagem oficial do Python como base
2
+ FROM python:3.9
3
+
4
+ # Cria um utilizador não-root para segurança
5
+ RUN useradd -m -u 1000 user
6
+ USER user
7
+ ENV PATH="/home/user/.local/bin:$PATH"
8
+
9
+ # Define o diretório de trabalho dentro do container
10
+ WORKDIR /app
11
+
12
+ # Copia o ficheiro de requisitos e instala as dependências PRIMEIRO
13
+ # Isto aproveita o cache do Docker e acelera builds futuras
14
+ COPY --chown=user ./requirements.txt requirements.txt
15
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
16
+
17
+ # Copia todos os outros ficheiros do projeto (app.py, pasta templates, etc.)
18
+ COPY --chown=user . /app
19
+
20
+ # Expõe a porta que a aplicação vai usar
21
+ EXPOSE 7860
22
+
23
+ # O comando para iniciar a aplicação EM PRODUÇÃO usando Gunicorn
24
+ # Gunicorn é um servidor WSGI robusto, ideal para Flask.
25
+ CMD ["gunicorn", "--workers", "4", "--bind", "0.0.0.0:7860", "app:app"]
README.md CHANGED
@@ -1,11 +1,10 @@
1
- ---
2
- title: Convertpcb
3
- emoji: 📉
4
- colorFrom: yellow
5
- colorTo: pink
6
- sdk: docker
7
- pinned: false
8
- license: other
9
- ---
10
-
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: PCB to Gerber Converter
3
+ emoji: 🔌
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ ---
7
+
8
+ # 🔌 PCB to Gerber Converter
9
+
10
+ Esta aplicação converte imagens de placas de circuito impresso (PCB) em ficheiros vetoriais Gerber, prontos para fabricação.
 
app.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py - VERSÃO FINAL, COMPLETA E CORRIGIDA
2
+
3
+ import os
4
+ import cv2
5
+ import numpy as np
6
+ import base64
7
+ import tempfile
8
+ import zipfile
9
+ import uuid
10
+ from flask import Flask, request, jsonify, render_template, send_from_directory
11
+ from werkzeug.utils import secure_filename
12
+
13
+ # --- CONFIGURAÇÃO DA APLICAÇÃO ---
14
+ app = Flask(__name__)
15
+ UPLOAD_FOLDER = tempfile.gettempdir()
16
+ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
17
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB
18
+
19
+ # --- FUNÇÕES DE PROCESSAMENTO DE IMAGEM ---
20
+
21
+ def process_image(image_path, options):
22
+ """
23
+ Função principal que orquestra o pipeline de processamento de imagem.
24
+ Versão corrigida para imagens com pistas brancas sobre fundo preto.
25
+ """
26
+ img = cv2.imread(image_path)
27
+ if img is None: raise ValueError("Não foi possível ler a imagem.")
28
+
29
+ # 1. Converter para escala de cinza
30
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
31
+
32
+ # 2. Pré-processamento (opcional, mas útil)
33
+ if options.get('enhance_contrast'):
34
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
35
+ gray = clahe.apply(gray)
36
+ if options.get('remove_noise'):
37
+ gray = cv2.medianBlur(gray, 3)
38
+
39
+ # 3. Binarização da imagem (CORRIGIDO)
40
+ # Usamos THRESH_BINARY: pixels claros (acima do threshold) ficam brancos.
41
+ _, binary_img = cv2.threshold(
42
+ gray, options.get('threshold'), 255, cv2.THRESH_BINARY
43
+ )
44
+
45
+ # 4. LIMPEZA AVANÇADA DOS CONTORNOS
46
+ kernel = np.ones((2, 2), np.uint8)
47
+ cleaned_img = cv2.morphologyEx(binary_img, cv2.MORPH_OPEN, kernel, iterations=2)
48
+ cleaned_img = cv2.morphologyEx(cleaned_img, cv2.MORPH_CLOSE, kernel, iterations=2)
49
+
50
+ # 5. Encontrar os contornos na imagem JÁ LIMPA
51
+ contours, _ = cv2.findContours(
52
+ cleaned_img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE
53
+ )
54
+
55
+ # 6. Filtrar contornos muito pequenos
56
+ min_area = options.get('min_area')
57
+ filtered_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > min_area]
58
+
59
+ if options.get('smooth_curves'):
60
+ smoothed_contours = [cv2.approxPolyDP(cnt, 0.001 * cv2.arcLength(cnt, True), True) for cnt in filtered_contours]
61
+ filtered_contours = smoothed_contours
62
+
63
+ # 7. Gerar pré-visualizações (a função agora existe)
64
+ previews = generate_previews(img, cleaned_img, filtered_contours)
65
+
66
+ return filtered_contours, previews
67
+
68
+ def generate_previews(original_img, binary_img, contours):
69
+ """
70
+ Função que gera imagens em Base64 para mostrar no frontend.
71
+ """
72
+ contour_preview = np.zeros_like(original_img)
73
+ cv2.drawContours(contour_preview, contours, -1, (102, 126, 234), 2)
74
+ def to_base64(img_array):
75
+ _, buffer = cv2.imencode('.png', img_array)
76
+ return base64.b64encode(buffer).decode('utf-8')
77
+ return {
78
+ 'original': to_base64(original_img),
79
+ 'binary': to_base64(binary_img), # Mostra a imagem binária já limpa
80
+ 'contours': to_base64(contour_preview)
81
+ }
82
+
83
+ # --- FUNÇÕES DE GERAÇÃO DE FICHEIROS ---
84
+
85
+ def create_gerber_manually(contours, img_height, dpi, output_path):
86
+ """
87
+ Cria um ficheiro Gerber a partir de contornos, sem bibliotecas externas.
88
+ """
89
+ scale_factor = 25.4 / dpi
90
+ precision = 10000
91
+ gerber_commands = ["%FSLAX44Y44*%", "%MOMM*%", "%LPD*%"]
92
+
93
+ for contour in contours:
94
+ gerber_commands.append("G36*")
95
+ first_point = contour[0][0]
96
+ x_mm = first_point[0] * scale_factor
97
+ y_mm = (img_height - first_point[1]) * scale_factor
98
+ gerber_commands.append(f"X{int(x_mm * precision)}Y{int(y_mm * precision)}D02*")
99
+ for point in contour[1:]:
100
+ p = point[0]
101
+ x_mm = p[0] * scale_factor
102
+ y_mm = (img_height - p[1]) * scale_factor
103
+ gerber_commands.append(f"X{int(x_mm * precision)}Y{int(y_mm * precision)}D01*")
104
+ gerber_commands.append(f"X{int(x_mm * precision)}Y{int(y_mm * precision)}D01*")
105
+ gerber_commands.append("G37*")
106
+ gerber_commands.append("M02*")
107
+ with open(output_path, 'w') as f:
108
+ f.write("\n".join(gerber_commands) + "\n")
109
+
110
+ def create_drill_file(contours, img_height, dpi, output_path):
111
+ drill_holes = []
112
+ for cnt in contours:
113
+ area = cv2.contourArea(cnt)
114
+ perimeter = cv2.arcLength(cnt, True)
115
+ if perimeter == 0: continue
116
+ circularity = 4 * np.pi * (area / (perimeter * perimeter))
117
+ if 0.8 < circularity < 1.2:
118
+ (x, y), radius = cv2.minEnclosingCircle(cnt)
119
+ x_inch, y_inch = x / dpi, (img_height - y) / dpi
120
+ diameter_inch = (radius * 2) / dpi
121
+ drill_holes.append({'x': x_inch, 'y': y_inch, 'd': diameter_inch})
122
+ if not drill_holes: return False
123
+ with open(output_path, 'w') as f:
124
+ f.write("M48\nINCH,LZ\nFMAT,2\n")
125
+ tools = {}
126
+ for hole in drill_holes:
127
+ d_str = f"{hole['d']:.4f}"
128
+ if d_str not in tools: tools[d_str] = []
129
+ tools[d_str].append(hole)
130
+ tool_id = 1
131
+ for d_str, _ in tools.items():
132
+ f.write(f"T{tool_id}C{d_str}\n"); tool_id += 1
133
+ f.write("%\n")
134
+ tool_id = 1
135
+ for _, holes in tools.items():
136
+ f.write(f"T{tool_id}\n")
137
+ for hole in holes: f.write(f"X{hole['x']:.4f}Y{hole['y']:.4f}\n")
138
+ tool_id += 1
139
+ f.write("M30\n")
140
+ return True
141
+
142
+ def create_svg(contours, width, height, dpi, output_path):
143
+ width_mm, height_mm = width / dpi * 25.4, height / dpi * 25.4
144
+ svg = f'<svg width="{width_mm}mm" height="{height_mm}mm" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">\n'
145
+ svg += '<style>.pcb-trace { fill: #2c9a55; stroke: #2c9a55; stroke-width: 0.5; }</style>\n'
146
+ svg += f'<g transform="translate(0, {height}) scale(1, -1)">\n'
147
+ for contour in contours:
148
+ points = " ".join([f"{p[0][0]},{p[0][1]}" for p in contour])
149
+ svg += f' <polygon class="pcb-trace" points="{points}" />\n'
150
+ svg += '</g>\n</svg>'
151
+ with open(output_path, "w") as f: f.write(svg)
152
+
153
+ # --- ROTAS DA API FLASK ---
154
+
155
+ @app.route('/')
156
+ def index(): return render_template('index.html')
157
+
158
+ @app.route('/process', methods=['POST'])
159
+ def process_route():
160
+ if 'image' not in request.files: return jsonify({'success': False, 'error': 'Nenhum ficheiro'}), 400
161
+ file = request.files['image']
162
+ if file.filename == '': return jsonify({'success': False, 'error': 'Nenhum ficheiro'}), 400
163
+ DPI = 600
164
+ try:
165
+ 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'}
166
+ filename = secure_filename(file.filename)
167
+ temp_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
168
+ file.save(temp_path)
169
+
170
+ # Chamada ao processamento
171
+ contours, previews = process_image(temp_path, options)
172
+
173
+ session_id = str(uuid.uuid4())
174
+ filenames = {'gbr': f"{session_id}.gbr", 'svg': f"{session_id}.svg", 'drl': f"{session_id}.drl", 'zip': f"{session_id}.zip"}
175
+ paths = {k: os.path.join(app.config['UPLOAD_FOLDER'], v) for k, v in filenames.items()}
176
+ img_h, img_w = cv2.imread(temp_path).shape[:2]
177
+
178
+ create_gerber_manually(contours, img_h, DPI, paths['gbr'])
179
+ create_svg(contours, img_w, img_h, DPI, paths['svg'])
180
+ with open(paths['svg'], 'rb') as f: previews['svg'] = base64.b64encode(f.read()).decode('utf-8')
181
+ drill_gen = create_drill_file(contours, img_h, DPI, paths['drl']) if options['generate_drill'] else False
182
+
183
+ with zipfile.ZipFile(paths['zip'], 'w') as zf:
184
+ zf.write(paths['gbr'], os.path.basename(paths['gbr']))
185
+ zf.write(paths['svg'], os.path.basename(paths['svg']))
186
+ if drill_gen: zf.write(paths['drl'], os.path.basename(paths['drl']))
187
+
188
+ 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}}}
189
+ os.remove(temp_path)
190
+ return jsonify(response_data)
191
+
192
+ except Exception as e:
193
+ app.logger.error(f"Erro no processamento: {e}", exc_info=True)
194
+ return jsonify({'success': False, 'error': str(e)}), 500
195
+
196
+ @app.route('/download/<path:filename>')
197
+ def download_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
198
+
199
+
200
+ if __name__ == '__main__':
201
+ app.run(debug=True, port=5000)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Flask
2
+ numpy
3
+ opencv-python-headless
4
+ gunicorn
5
+ fastapi
6
+ uvicorn[standard]