-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
425 lines (345 loc) · 10.7 KB
/
main.py
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
import threading
import copy
from ultralytics import YOLO
from GoGame import *
from GoBoard import *
from GoVisual import *
from flask import Flask, render_template, Response, request
import cv2
import base64
import time
import recup_os
#cam_index = 0
def find_camera_index():
index = 0
while True:
cap = cv2.VideoCapture(index)
if cap.read()[0]:
cap.release()
return index
cap.release()
index += 1
cam_index = find_camera_index()
app = Flask(__name__, static_url_path='/static')
app.secret_key = 'your_secret_key'
model = YOLO('model.pt')
usual_message = "La caméra est bien fixée et tout est Ok"
message = "Rien n'a encore été lancé "
disabled_button = 'stop-button'
ProcessFrame = None
Process = True
initialized = False
sgf_text = None
empty_board = cv2.imread("empty_board.jpg")
game_plot = empty_board
process_thread = None
go_game = None
transparent_mode = False
endGame = False
def New_game(transparent_mode=False):
global go_game, initialized, game_plot
game = sente.Game()
go_visual = GoVisual(game)
go_board = GoBoard(model)
go_game = GoGame(game, go_board, go_visual, transparent_mode)
game_plot = empty_board
initialized = False
def processing_thread():
"""
Process the detection algorithm
Update:
game_plot, sgf_text
Send error to message if there is one
"""
global ProcessFrame, game_plot, message, initialized, sgf_text
if not ProcessFrame is None:
try:
if not initialized:
game_plot, sgf_text = go_game.initialize_game(ProcessFrame, endGame)
initialized = True
message = usual_message
else:
game_plot, sgf_text = go_game.main_loop(ProcessFrame, endGame)
message = usual_message
except Exception as e:
message = "Erreur : "+str(e)
def generate_plot():
"""
Generate a plot representing the game
Returns:
Image
"""
global game_plot
processing_thread()
if transparent_mode:
to_plot = game_plot
else:
to_plot = go_game.go_visual.current_position()
_, img_encoded = cv2.imencode('.jpg', to_plot)
img_base64 = base64.b64encode(img_encoded).decode('utf-8')
return img_base64
# def end_camera():
# global process_thread, camera_running, disabled_button
# if camera_running:
# process_thread.join() # Wait for the thread to finish before stopping
# camera_running = False
# disabled_button = 'stop-button' # Define the ID of the button to desactivate
# def open_camera():
# """Open the camera"""
# global camera, process_thread, disabled_button, camera_running
# if not camera_running:
# camera = cv2.VideoCapture(cam_index, cv2.CAP_DSHOW)
# process_thread = threading.Thread(target=processing_thread, args=(camera,))
# process_thread.start()
# camera_running = True
# disabled_button = 'start-button' # Define the ID of the button to desactivate
@app.route('/')
def index():
"""Route to display HTML page"""
return render_template('home.html', disabled_button=disabled_button)
@app.route('/update')
def afficher_message():
"""
Route to update the image and the message to display
Returns:
message
image
"""
return {'message': message, 'image' : generate_plot()}
def generate_frames():
"""
Generate an image from the video stream
Returns:
Image
"""
global ProcessFrame, camera
while True:
try:
success, frame = camera.read() # Read the image from the camera
if not success:
break
else:
ProcessFrame = copy.deepcopy(frame)
_, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
time.sleep(0.05)
except Exception:
print('Exception: Camera not detected')
break
@app.route('/video_feed')
def video_feed():
"""
Route to send the video stream
"""
print("in video feed")
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
def end_camera():
"""stop the camera """
global camera
camera.release()
def open_camera():
"""open the camera """
global camera
os = recup_os.get_os()
if os == "Windows" :
camera = cv2.VideoCapture(cam_index, cv2.CAP_DSHOW)
elif os == "Linux" :
camera = cv2.VideoCapture(cam_index, cv2.V4L2)
else :
camera = cv2.VideoCapture(cam_index)
try :
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
except :
pass
@app.route('/cam', methods=['POST', 'GET'])
def getval():
"""
Route to send the video stream
"""
global disabled_button, transparent_mode
transparent_mode = False
try:
k = request.form['psw1']
if k == '0':
open_camera()
if camera.read()[0]:
New_game()
disabled_button = 'start-button'
elif k == '1':
end_camera()
disabled_button = 'stop-button'
except Exception:
print("Exception: Page can not be refreshed")
return render_template('partie.html', disabled_button=disabled_button)
@app.route('/t', methods=['POST', 'GET'])
def getvaltransparent():
"""
Route to send the video stream
"""
global disabled_button, transparent_mode
transparent_mode = True
try:
k = request.form['psw1']
if k == '0':
open_camera()
if camera.read()[0]:
New_game(True)
disabled_button = 'start-button'
elif k == '1':
end_camera()
disabled_button = 'stop-button'
except Exception:
print("Exception: Page can not be refreshed")
return render_template('transparent.html', disabled_button=disabled_button)
@app.route('/game', methods=['POST'])
def getval2():
"""
Change the current move
"""
global transparent_mode
transparent_mode = False
i = request.form['psw2']
if i =='2':
go_game.go_visual.initial_position()
elif i == '3':
go_game.go_visual.previous()
elif i == '4':
go_game.go_visual.next()
elif i == '5':
go_game.go_visual.final_position()
print(i)
return render_template('partie.html', disabled_button=disabled_button)
@app.route('/sgf_controls', methods=['POST'])
def getval3():
"""
Change the current move
"""
global transparent_mode
transparent_mode = False
i = request.form['psw2']
if i =='2':
go_game.go_visual.initial_position()
elif i == '3':
go_game.go_visual.previous()
elif i == '4':
go_game.go_visual.next()
elif i == '5':
go_game.go_visual.final_position()
print(i)
return render_template('sgf.html', disabled_button=disabled_button)
@app.route('/rules', methods=['POST'])
def handle_rules():
"""
Check if we want to apply rules, still not implemented
"""
global rules_applied, transparent_mode
transparent_mode = False
rules_applied = request.form['psw3']
if rules_applied == "True":
go_game.set_transparent_mode(False)
rules_applied = "False"
else :
go_game.set_transparent_mode(True)
print("########pas de regles")
rules_applied = "True"
return render_template('partie.html', disabled_button=disabled_button)
@app.route('/change_place', methods=['POST'])
def change_place():
"""
Route to get the piece that we want to change its position
"""
global transparent_mode
transparent_mode = False
old_pos = request.form['input1']
new_pos = request.form['input2']
try:
go_game.correct_stone(old_pos,new_pos)
except Exception as e:
message = "L'erreur est "+str(e)
return render_template('partie.html', disabled_button=disabled_button)
@app.route('/get_sgf_txt')
def get_sgf_txt():
"""
Route which returns the sgf text to be uploaded
"""
global transparent_mode
global sgf_text
if transparent_mode:
sgf_text = go_game.post_treatment(True)
return sgf_text
@app.route('/upload', methods=['POST'])
def process():
"""
Route which enables us to save the sgf text
"""
global transparent_mode
transparent_mode = False
file = request.files['file']
file_path = file.filename
try:
go_game.go_visual.load_game_from_sgf(file_path)
message = "Le fichier a été correctement chargé"
except Exception as e:
message = "L'erreur est "+str(e)
return render_template('sgf.html', disabled_button=disabled_button)
@app.route('/Home')
def home():
"""
Route to get to the home page
"""
open_camera()
return render_template('Home.html', disabled_button=disabled_button)
@app.route('/credit')
def credit():
"""
Route to get to the credit page
"""
return render_template("credits.html")
@app.route('/undo', methods=['POST'])
def undo():
"""
undo last played move
"""
global transparent_mode
transparent_mode = False
go_game.delete_last_move()
return render_template("partie.html")
@app.route('/historique')
def historique():
"""
Route to get to the summary page
"""
return render_template("Historique.html")
@app.route('/partie')
def partie():
"""
Route to get to the streaming page in game mode
"""
global transparent_mode
transparent_mode = False
return render_template("partie.html", disabled_button=disabled_button)
@app.route('/transparent')
def transparent():
"""
Route to get to the streaming page in transparent mode
"""
go_game.set_transparent_mode(True)
global transparent_mode
transparent_mode = False
return render_template("transparent.html")
@app.route('/sgf')
def sgf():
"""
Route to get to the streaming page in transparent mode
"""
global transparent_mode
transparent_mode = False
return render_template("sgf.html")
if __name__ == '__main__':
New_game()
# process_thread = threading.Thread(target=processing_thread, args=())
# process_thread.start()
app.run(debug=True)