-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
577 lines (467 loc) · 20.5 KB
/
main.py
File metadata and controls
577 lines (467 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
import os
import uuid
import threading
import csv
import cv2
import numpy as np
import pandas as pd
from CannyEdge import Canny_detector
from polygonOutline import draw_polygon_outlines
from datetime import datetime
from time import sleep
from io import BytesIO
from gCode import path_to_gcode
from arduino_interface import ArduinoInterface, send_gcode_file, detect_serial_port
from serial.serialutil import SerialException
from flask import Flask, jsonify, request, send_file
from flask_cors import CORS
from werkzeug.utils import secure_filename
# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['PROCESSED_FOLDER'] = 'processed'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})
# Create directories if they don't exist
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['PROCESSED_FOLDER'], exist_ok=True)
# In-memory job storage (use Redis in production)
jobs = {}
# Arduino connection state
arduino_connection = {
'connected': False,
'port': None,
'interface': None,
'last_check': None
}
# Allowed file extensions
ALLOWED_EXTENSIONS = {'png', 'jpg'}
# Sort polygons by area (smallest to largest)
def sort_polygons_by_area(contours, sort_by='area'):
if sort_by == 'area':
return sorted(contours, key=cv2.contourArea)
elif sort_by == 'perimeter':
return sorted(contours, key=cv2.arcLength)
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def apply_edge_detection(input_path, output_path, job_id):
"""Apply edge detection to image in background thread and generate G-code"""
try:
jobs[job_id]['status'] = 'processing'
jobs[job_id]['progress'] = 10
img = cv2.imread(input_path)
if img is None:
raise Exception("Could not read the image file.")
jobs[job_id]['progress'] = 30
edges = Canny_detector(img)
contours, _ = cv2.findContours(edges.astype('uint8'), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
jobs[job_id]['progress'] = 50
MIN_CONTOUR_AREA = 0.0
contours = [c for c in contours if cv2.contourArea(c) > MIN_CONTOUR_AREA]
sorted_contours = sort_polygons_by_area(contours, sort_by='area')
jobs[job_id]['sorted_contours'] = sorted_contours
jobs[job_id]['contour_count'] = len(sorted_contours)
result = draw_polygon_outlines(img, sorted_contours)
cv2.imwrite(output_path, result)
jobs[job_id]['progress'] = 70
# Generate G-code automatically
print(f"[{job_id}] Starting G-code generation...")
slider = jobs[job_id].get('slider', 100)
total = len(sorted_contours)
n = max(1, int(round(total * (slider / 100.0)))) if slider < 100 else total
contours_to_use = sorted_contours[-n:]
print(f"[{job_id}] Total contours: {total}, Using: {n}")
# Convert to paths format
paths = contours_to_paths(contours_to_use)
print(f"[{job_id}] Converted to {len(paths)} paths")
# Calculate scale factor to convert pixels to mm
# Drawing space: 316.8mm (width) x 178.2mm (height), origin at bottom-left
DRAWING_WIDTH_MM = 220
DRAWING_HEIGHT_MM = 120
img_height, img_width = img.shape[:2]
# Scale to fit within drawing space while preserving aspect ratio
scale_x = DRAWING_WIDTH_MM / img_width
scale_y = DRAWING_HEIGHT_MM / img_height
scale = min(scale_x, scale_y) # Use smaller scale to fit within bounds
# Calculate actual drawing size after scaling
scaled_width = img_width * scale
scaled_height = img_height * scale
# Center the drawing in the available space
offset_x = (DRAWING_WIDTH_MM - scaled_width) / 2
offset_y = (DRAWING_HEIGHT_MM - scaled_height) / 2
print(f"[{job_id}] Image size: {img_width}x{img_height}px")
print(f"[{job_id}] Drawing space: {DRAWING_WIDTH_MM}x{DRAWING_HEIGHT_MM}mm")
print(f"[{job_id}] Scaled size: {scaled_width:.2f}x{scaled_height:.2f}mm")
print(f"[{job_id}] Scale: {scale:.4f}, Offsets: ({offset_x:.2f}, {offset_y:.2f})mm")
# Always save to the same filename (overwrites previous)
gcode_path = os.path.join(os.path.dirname(__file__), 'output.gcode') # Save in main folder
path_to_gcode(gcode_path, paths, z_safe=110.0, z_cut=50.0,
feed_xy=1500, feed_z=3000, scale=scale, offset_x=offset_x, offset_y=offset_y)
jobs[job_id]['gcode_path'] = gcode_path
jobs[job_id]['progress'] = 90
sleep(1)
jobs[job_id]['progress'] = 100
jobs[job_id]['status'] = 'completed'
jobs[job_id]['result_path'] = output_path
jobs[job_id]['completed_at'] = datetime.now().isoformat()
except Exception as e:
jobs[job_id]['status'] = 'failed'
jobs[job_id]['error'] = str(e)
jobs[job_id]['completed_at'] = datetime.now().isoformat()
print(f"[{job_id}] ERROR: {str(e)}")
import traceback
traceback.print_exc()
# Convert OpenCV contours to the format expected by path_to_gcode
def contours_to_paths(contours):
"""Convert OpenCV contours to list of (x,y) tuples for G-code generation"""
paths = []
for contour in contours:
# contour shape is (N, 1, 2), reshape to (N, 2)
path = [(float(pt[0]), float(pt[1])) for pt in contour.reshape(-1, 2)]
paths.append(path)
return paths
def generate_outline_gcode(output_path, width_mm=227.3, height_mm=127.9, z_safe=150.0, z_cut=50.0):
"""Generate G-code to outline the drawing area rectangle"""
# Convert mm to meters
width_m = width_mm / 1000.0
height_m = height_mm / 1000.0
z_safe_m = z_safe / 1000.0
z_cut_m = z_cut / 1000.0
with open(output_path, 'w') as f:
f.write("; Drawing Area Outline\n")
f.write("; Origin: Bottom-left (0, 0)\n")
f.write(f"; Size: {width_mm}mm x {height_mm}mm\n")
f.write("G90 ; Absolute positioning\n")
f.write("\n")
# Move to safe height
f.write(f"G0 Z{z_safe_m:.6f} ; Move to safe height\n")
# Move to bottom-left corner (0, 0, z_safe)
f.write(f"G0 X0.000000 Y0.000000 Z{z_safe_m:.6f} ; Bottom-left corner\n")
# Lower to drawing height (z_cut, not 0)
f.write(f"G1 Z{z_cut_m:.6f} F3000 ; Lower to drawing height\n")
# Trace rectangle: (0,0) → (width,0) → (width,height) → (0,height) → (0,0)
f.write(f"G1 X{width_m:.6f} Y0.000000 F1500 ; Bottom edge\n")
f.write(f"G1 X{width_m:.6f} Y{height_m:.6f} F1500 ; Right edge\n")
f.write(f"G1 X0.000000 Y{height_m:.6f} F1500 ; Top edge\n")
f.write(f"G1 X0.000000 Y0.000000 F1500 ; Left edge back to origin\n")
# Raise to safe height
f.write(f"G0 Z{z_safe_m:.6f} ; Raise to safe height\n")
f.write("\n")
f.write("; End of outline\n")
# sanity check route
@app.route('/ping', methods=['GET'])
def ping_pong():
return jsonify('pong!')
# sanity check route
@app.route('/config', methods=['GET'])
def provide_config():
return jsonify({
'allowed_extensions': list(ALLOWED_EXTENSIONS),
})
@app.route('/upload', methods=['POST'])
def handle_upload():
"""Upload image and start edge detection processing"""
if 'file' not in request.files:
return jsonify({'error': 'No file provided'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected'}), 400
if not allowed_file(file.filename):
return jsonify({'error': 'File type not allowed'}), 400
# Generate job ID with a radnom file name
job_id = str(uuid.uuid4())
filename = secure_filename(file.filename)
input_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{job_id}_{filename}")
output_path = os.path.join(app.config['PROCESSED_FOLDER'], f"{job_id}_edges_{filename}")
# Save uploaded file
file.save(input_path)
# sanitize and parse slider value (default 100)
slider_raw = request.form.get('slider')
try:
slider_val = int(slider_raw) if slider_raw is not None else 100
except ValueError:
slider_val = 100
slider_val = max(1, min(100, slider_val))
# Create job record
jobs[job_id] = {
'id': job_id,
'status': 'queued',
'progress': 0,
'created_at': datetime.now().isoformat(),
'original_filename': filename,
'input_path': input_path,
'output_path': output_path,
'slider': slider_val
}
# log saved slider so you can verify server got it
print(f"[{job_id}] Uploaded with slider={slider_val}")
# Start background processing, use a dummy image output for now
thread = threading.Thread(target=apply_edge_detection, args=(input_path, output_path, job_id))
thread.daemon = True
thread.start()
return jsonify({
'job_id': job_id,
'status': 'queued',
'message': 'Image uploaded successfully, processing started'
}), 202
@app.route('/jobs/<job_id>/render', methods=['GET'])
def render_with_slider(job_id):
"""Render cached contours with a slider-controlled amount (after processing)."""
if job_id not in jobs:
return jsonify({'error': 'Job not found'}), 404
job = jobs[job_id]
if job.get('status') != 'completed':
return jsonify({'error': 'Job not completed yet'}), 400
sorted_contours = job.get('sorted_contours')
if not sorted_contours:
return jsonify({'error': 'No contours cached for this job'}), 400
slider = request.args.get('slider', type=int)
if slider is None:
slider = job.get('slider', 100)
# clamp slider
slider = max(1, min(100, int(slider)))
total = len(sorted_contours)
# Interpret slider 1..100 as percentage of total contours.
# slider=None or slider>=100 => show all
if slider is None or slider >= 100:
n = total
elif slider <= 0:
n = 1
else:
# use rounding to avoid losing contours due to truncation
n = max(1, int(round(total * (slider / 100.0))))
print(f"[{job_id}] Rendering with slider={slider}, n={n} of {total} contours.")
img = cv2.imread(job['input_path'])
if img is None:
return jsonify({'error': 'Original image missing'}), 500
# sorted_contours is ascending by area. Show the largest N polygons first:
contours_to_draw = sorted_contours[-n:] if n > 0 else []
rendered = draw_polygon_outlines(img, contours_to_draw)
ok, png = cv2.imencode('.png', rendered)
if not ok:
return jsonify({'error': 'Failed to encode image'}), 500
return send_file(
BytesIO(png.tobytes()),
mimetype='image/png',
as_attachment=False,
download_name=f"render_{job['original_filename']}.png"
)
@app.route('/jobs/<job_id>/status', methods=['GET'])
def get_job_status(job_id):
"""Get processing status of a job"""
if job_id not in jobs:
return jsonify({'error': 'Job not found'}), 404
job = jobs[job_id]
response = {
'job_id': job_id,
'status': job['status'],
'progress': job['progress'],
'created_at': job['created_at'],
'contour_count': job.get('contour_count', 0),
'slider': job.get('slider', 100),
'execution_status': job.get('execution_status'),
'execution_progress': job.get('execution_progress', 0),
'execution_error': job.get('execution_error')
}
if job['status'] == 'completed':
# point frontend to the render endpoint and include the stored slider
response['download_url'] = f'/jobs/{job_id}/render?slider={job.get("slider", 100)}'
response['completed_at'] = job['completed_at']
elif job['status'] == 'failed':
response['error'] = job['error']
response['completed_at'] = job['completed_at']
return jsonify(response)
@app.route('/jobs/<job_id>/download', methods=['GET'])
def download_result(job_id):
"""Download processed image"""
if job_id not in jobs:
return jsonify({'error': 'Job not found'}), 404
job = jobs[job_id]
if job['status'] != 'completed':
return jsonify({'error': 'Job not completed yet'}), 400
if not os.path.exists(job['result_path']):
return jsonify({'error': 'Processed file not found'}), 404
return send_file(
job['result_path'],
as_attachment=True,
download_name=f"edges_{job['original_filename']}"
)
@app.route('/jobs/<job_id>/gcode', methods=['GET'])
def generate_gcode(job_id):
"""Generate G-code from processed contours"""
if job_id not in jobs:
return jsonify({'error': 'Job not found'}), 404
job = jobs[job_id]
if job.get('status') != 'completed':
return jsonify({'error': 'Job not completed yet'}), 400
sorted_contours = job.get('sorted_contours')
if not sorted_contours:
return jsonify({'error': 'No contours found'}), 400
# Get slider value to determine how many contours to include
slider = request.args.get('slider', type=int, default=job.get('slider', 100))
slider = max(1, min(100, int(slider)))
total = len(sorted_contours)
n = max(1, int(round(total * (slider / 100.0)))) if slider < 100 else total
# Take largest N contours
contours_to_use = sorted_contours[-n:]
# Convert contours to paths format
paths = contours_to_paths(contours_to_use)
# Generate G-code file
gcode_filename = f"{job_id}_output.gcode"
gcode_path = os.path.join(app.config['PROCESSED_FOLDER'], gcode_filename)
# Get optional parameters from query string
z_safe = request.args.get('z_safe', type=float, default=100.0)
z_cut = request.args.get('z_cut', type=float, default=0.0)
feed_xy = request.args.get('feed_xy', type=float, default=1500)
feed_z = request.args.get('feed_z', type=float, default=3000)
path_to_gcode(gcode_path, paths, z_safe=z_safe, z_cut=z_cut,
feed_xy=feed_xy, feed_z=feed_z)
return send_file(
gcode_path,
as_attachment=True,
download_name=f"contours_{job['original_filename']}.gcode"
)
@app.route('/jobs', methods=['GET'])
def list_jobs():
"""list all jobs"""
return jsonify([{
'job_id': job_id,
'status': job['status'],
'progress': job['progress'],
'created_at': job['created_at'],
'original_filename': job['original_filename']
} for job_id, job in jobs.items()])
def execute_gcode_background(job_id, gcode_path, show_outline=False):
"""Execute G-code in background thread"""
try:
# Update job status
jobs[job_id]['execution_status'] = 'connecting'
jobs[job_id]['execution_progress'] = 0
# Connect to Arduino if not already connected
if not arduino_connection['connected'] or arduino_connection['interface'] is None:
port = arduino_connection['port'] or detect_serial_port()
if not port:
raise Exception("No Arduino found. Please connect Arduino and try again.")
print(f"[{job_id}] Detected port: {port}")
print(f"[{job_id}] Connecting to Arduino on {port}...")
try:
arduino_connection['interface'] = ArduinoInterface(port=port)
arduino_connection['connected'] = True
arduino_connection['port'] = port
print(f"[{job_id}] Connected to Arduino")
except PermissionError as e:
raise Exception(f"Permission denied accessing {port}. On Linux, add your user to the 'dialout' group: sudo usermod -a -G dialout $USER (then logout/login)")
except Exception as e:
raise Exception(f"Failed to connect to {port}: {str(e)}")
jobs[job_id]['execution_status'] = 'executing'
jobs[job_id]['execution_progress'] = 10
# Send outline preview if requested
if show_outline:
print(f"[{job_id}] Generating and sending drawing area outline preview...")
outline_path = os.path.join(os.path.dirname(__file__), 'outline_preview.gcode')
generate_outline_gcode(outline_path)
outline_success = send_gcode_file(arduino_connection['interface'], outline_path)
if not outline_success:
raise Exception("Failed to send outline preview to Arduino")
print(f"[{job_id}] Outline preview completed. Waiting 5 seconds before drawing...")
jobs[job_id]['execution_progress'] = 30
sleep(5)
jobs[job_id]['execution_progress'] = 40
# Send actual drawing G-code file
print(f"[{job_id}] Sending drawing G-code file: {gcode_path}")
success = send_gcode_file(arduino_connection['interface'], gcode_path)
if success:
jobs[job_id]['execution_status'] = 'completed'
jobs[job_id]['execution_progress'] = 100
print(f"[{job_id}] G-code execution completed successfully")
else:
jobs[job_id]['execution_status'] = 'failed'
jobs[job_id]['execution_error'] = 'Failed to send G-code to Arduino'
print(f"[{job_id}] G-code execution failed")
except SerialException as e:
jobs[job_id]['execution_status'] = 'failed'
jobs[job_id]['execution_error'] = f'Arduino connection error: {str(e)}'
arduino_connection['connected'] = False
arduino_connection['interface'] = None
print(f"[{job_id}] Serial error: {e}")
except Exception as e:
jobs[job_id]['execution_status'] = 'failed'
jobs[job_id]['execution_error'] = str(e)
print(f"[{job_id}] Execution error: {e}")
import traceback
traceback.print_exc()
@app.route('/arduino/status', methods=['GET'])
def arduino_status():
"""Check Arduino connection status"""
# Try to detect Arduino if not connected
if not arduino_connection['connected']:
port = detect_serial_port()
return jsonify({
'connected': False,
'port': port,
'available': port is not None
})
return jsonify({
'connected': True,
'port': arduino_connection['port']
})
@app.route('/arduino/connect', methods=['POST'])
def arduino_connect():
"""Manually connect to Arduino"""
try:
# Get port from request or auto-detect
data = request.get_json() or {}
port = data.get('port') or detect_serial_port()
if not port:
return jsonify({'error': 'No Arduino found'}), 404
# Close existing connection if any
if arduino_connection['interface']:
try:
arduino_connection['interface'].close()
except:
pass
# Connect
arduino_connection['interface'] = ArduinoInterface(port=port)
arduino_connection['connected'] = True
arduino_connection['port'] = port
return jsonify({
'connected': True,
'port': port,
'message': 'Connected to Arduino successfully'
})
except SerialException as e:
arduino_connection['connected'] = False
arduino_connection['interface'] = None
return jsonify({'error': f'Connection failed: {str(e)}'}), 500
@app.route('/jobs/<job_id>/execute', methods=['POST'])
def execute_job(job_id):
"""Send G-code to Arduino for execution"""
if job_id not in jobs:
return jsonify({'error': 'Job not found'}), 404
job = jobs[job_id]
if job.get('status') != 'completed':
return jsonify({'error': 'Job not completed yet'}), 400
# Check if G-code file exists
gcode_path = job.get('gcode_path')
if not gcode_path or not os.path.exists(gcode_path):
return jsonify({'error': 'G-code file not found'}), 404
# Check if already executing
if job.get('execution_status') == 'executing':
return jsonify({'error': 'Job is already executing'}), 400
# Get outline preview option from request body (default: False)
data = request.get_json() or {}
show_outline = data.get('show_outline', False)
# Start execution in background thread
thread = threading.Thread(target=execute_gcode_background, args=(job_id, gcode_path, show_outline))
thread.daemon = True
thread.start()
return jsonify({
'job_id': job_id,
'message': 'G-code execution started',
'execution_status': 'connecting',
'show_outline': show_outline
}), 202
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)