Fixed progress bar and added progress bar help text

This commit is contained in:
FrederikBaerentsen 2024-04-25 21:41:14 +02:00
parent 525169ef77
commit 3ea9a957ac
2 changed files with 111 additions and 60 deletions

89
app.py
View File

@ -47,14 +47,15 @@ def start_task(data):
if input_value not in total_set_file: if input_value not in total_set_file:
print('ERROR: ' + input_value) print('ERROR: ' + input_value)
# Reload create.html with error message # Reload create.html with error message
socketio.emit('task_failed', {'error': 'set_num'}, namespace='/progress') socketio.emit('task_failed', namespace='/progress')
return render_template('create.html',error=input_value) #return render_template('create.html',error=input_value)
# Start the task in a separate thread to avoid blocking the serve # Start the task in a separate thread to avoid blocking the serve
print('starting servers') else:
thread = Thread(target=new_set, args=(input_value,)) print('starting servers')
thread.start() thread = Thread(target=new_set, args=(input_value,))
thread.start()
#return redirect('/') #return redirect('/')
@ -77,13 +78,17 @@ def delete(tmp):
conn.close() conn.close()
return redirect('/') return redirect('/')
def progress(count,total_parts,state):
print (state)
socketio.emit('update_progress', {'progress': int(count/total_parts*100), 'desc': state}, namespace='/progress')
def new_set(set_num): def new_set(set_num):
global count global count
###### total count #### ###### total count ####
# 1 for set # 1 for set
# 1 for set image # 1 for set image
total_parts = 4 total_parts = 20
@ -92,20 +97,29 @@ def new_set(set_num):
# print("Input value:", set_num) # print("Input value:", set_num)
# print("Add duplicate:", add_duplicate) # print("Add duplicate:", add_duplicate)
# You can perform any further processing or redirect to another page # You can perform any further processing or redirect to another page
# >>>>>>>>
progress(count, total_parts,'Opening database')
conn = sqlite3.connect('app.db') conn = sqlite3.connect('app.db')
cursor = conn.cursor() cursor = conn.cursor()
# >>>>>>>>
progress(count, total_parts,'Adding set: ' + set_num)
print ("Adding set: " + set_num)
with open('api','r') as f: with open('api','r') as f:
api_key = f.read().replace('\n','') api_key = f.read().replace('\n','')
rb = rebrick.init(api_key) rb = rebrick.init(api_key)
# >>>>>>>>
progress(count, total_parts,'Generating Unique ID')
unique_set_id = generate_unique_set_unique() unique_set_id = generate_unique_set_unique()
# Get Set info and add to SQL # Get Set info and add to SQL
response = '' response = ''
# try:
# >>>>>>>>
progress(count, total_parts,'Get set info')
response = json.loads(rebrick.lego.get_set(set_num).read()) response = json.loads(rebrick.lego.get_set(set_num).read())
# except Exception as e: # except Exception as e:
@ -114,7 +128,10 @@ def new_set(set_num):
# return render_template('create.html',error=set_num) # return render_template('create.html',error=set_num)
count+=1 count+=1
socketio.emit('update_progress', {'progress': int(count/total_parts*100)}, namespace='/progress')
# >>>>>>>>
progress(count, total_parts,'Adding set to database')
cursor.execute('''INSERT INTO sets ( cursor.execute('''INSERT INTO sets (
set_num, set_num,
name, name,
@ -139,9 +156,14 @@ def new_set(set_num):
#print('Saving set image:',end='') #print('Saving set image:',end='')
# >>>>>>>>
progress(count, total_parts,'Get set image')
res = requests.get(set_img_url, stream = True) res = requests.get(set_img_url, stream = True)
count+=1 count+=1
if res.status_code == 200: if res.status_code == 200:
# >>>>>>>>
progress(count, total_parts,'Saving set image')
with open("./static/sets/"+set_num+".jpg",'wb') as f: with open("./static/sets/"+set_num+".jpg",'wb') as f:
shutil.copyfileobj(res.raw, f) shutil.copyfileobj(res.raw, f)
#print(' OK') #print(' OK')
@ -152,10 +174,12 @@ def new_set(set_num):
# Get inventory and add to SQL # Get inventory and add to SQL
# >>>>>>>>
progress(count, total_parts,'Get set inventory')
response = json.loads(rebrick.lego.get_set_elements(set_num,page_size=20000).read()) response = json.loads(rebrick.lego.get_set_elements(set_num,page_size=20000).read())
count+=1 count+=1
total_parts += len(response['results']) total_parts += len(response['results'])
socketio.emit('update_progress', {'progress': int(count/total_parts*100)}, namespace='/progress')
for i in response['results']: for i in response['results']:
if i['is_spare']: if i['is_spare']:
continue continue
@ -178,7 +202,8 @@ def new_set(set_num):
#print(">>> " + str(part_img_url)) #print(">>> " + str(part_img_url))
print(str(e)) print(str(e))
# >>>>>>>>
progress(count, total_parts,'Adding ' + i['part']['name'] + ' to database')
cursor.execute('''INSERT INTO inventory ( cursor.execute('''INSERT INTO inventory (
set_num, set_num,
id, id,
@ -198,10 +223,13 @@ def new_set(set_num):
if not Path("./static/parts/"+part_img_url_id+".jpg").is_file(): if not Path("./static/parts/"+part_img_url_id+".jpg").is_file():
#print('Saving part image:',end='') #print('Saving part image:',end='')
if part_img_url is not None: if part_img_url is not None:
# >>>>>>>>
progress(count, total_parts,'Get part image')
res = requests.get(part_img_url, stream = True) res = requests.get(part_img_url, stream = True)
count+=1 count+=1
socketio.emit('update_progress', {'progress': count}, namespace='/progress')
if res.status_code == 200: if res.status_code == 200:
# >>>>>>>>
progress(count, total_parts,'Saving part image')
with open("./static/parts/"+part_img_url_id+".jpg",'wb') as f: with open("./static/parts/"+part_img_url_id+".jpg",'wb') as f:
shutil.copyfileobj(res.raw, f) shutil.copyfileobj(res.raw, f)
#print(' OK') #print(' OK')
@ -219,9 +247,11 @@ def new_set(set_num):
# Get minifigs # Get minifigs
#print('Savings minifigs') #print('Savings minifigs')
tmp_set_num = set_num tmp_set_num = set_num
# >>>>>>>>
progress(count, total_parts,'Get set minifigs')
response = json.loads(rebrick.lego.get_set_minifigs(set_num).read()) response = json.loads(rebrick.lego.get_set_minifigs(set_num).read())
count+=1 count+=1
socketio.emit('update_progress', {'progress': int(count/total_parts*100)}, namespace='/progress')
#print(response) #print(response)
for i in response['results']: for i in response['results']:
@ -232,10 +262,13 @@ def new_set(set_num):
#print('Saving set image:',end='') #print('Saving set image:',end='')
if not Path("./static/minifigs/"+set_num+".jpg").is_file(): if not Path("./static/minifigs/"+set_num+".jpg").is_file():
if set_img_url is not None: if set_img_url is not None:
# >>>>>>>>
progress(count, total_parts,'Get minifig image')
res = requests.get(set_img_url, stream = True) res = requests.get(set_img_url, stream = True)
count+=1 count+=1
socketio.emit('update_progress', {'progress': int(count/total_parts*100)}, namespace='/progress')
if res.status_code == 200: if res.status_code == 200:
# >>>>>>>>
progress(count, total_parts,'Saving minifig image')
with open("./static/minifigs/"+set_num+".jpg",'wb') as f: with open("./static/minifigs/"+set_num+".jpg",'wb') as f:
shutil.copyfileobj(res.raw, f) shutil.copyfileobj(res.raw, f)
#print(' OK') #print(' OK')
@ -245,7 +278,8 @@ def new_set(set_num):
#print(' ERROR') #print(' ERROR')
else: else:
print(i) print(i)
# >>>>>>>>
progress(count, total_parts,'Adding minifig to database')
cursor.execute('''INSERT INTO minifigures ( cursor.execute('''INSERT INTO minifigures (
fig_num, fig_num,
set_num, set_num,
@ -258,9 +292,10 @@ def new_set(set_num):
conn.commit() conn.commit()
# Get minifigs inventory # Get minifigs inventory
# >>>>>>>>
progress(count, total_parts,'Get minifig inventory')
response_minifigs = json.loads(rebrick.lego.get_minifig_elements(i['set_num']).read()) response_minifigs = json.loads(rebrick.lego.get_minifig_elements(i['set_num']).read())
count+=1 count+=1
socketio.emit('update_progress', {'progress': int(count/total_parts*100)}, namespace='/progress')
for i in response_minifigs['results']: for i in response_minifigs['results']:
# Get part image. Saved under ./static/parts/xxxx.jpg # Get part image. Saved under ./static/parts/xxxx.jpg
@ -275,11 +310,14 @@ def new_set(set_num):
#print("Part number:", part_img_url_id) #print("Part number:", part_img_url_id)
if not Path("./static/parts/"+part_img_url_id+".jpg").is_file(): if not Path("./static/parts/"+part_img_url_id+".jpg").is_file():
#print('Saving part image:',end='') #print('Saving part image:',end='')
# >>>>>>>>
progress(count, total_parts,'Get minifig image')
res = requests.get(part_img_url, stream = True) res = requests.get(part_img_url, stream = True)
count+=1 count+=1
socketio.emit('update_progress', {'progress': int(count/total_parts*100)}, namespace='/progress')
if res.status_code == 200: if res.status_code == 200:
# >>>>>>>>
progress(count, total_parts,'Saving minifig image')
with open("./static/parts/"+part_img_url_id+".jpg",'wb') as f: with open("./static/parts/"+part_img_url_id+".jpg",'wb') as f:
shutil.copyfileobj(res.raw, f) shutil.copyfileobj(res.raw, f)
#print(' OK') #print(' OK')
@ -293,7 +331,8 @@ def new_set(set_num):
#print("Part number not found in the URL.") #print("Part number not found in the URL.")
#print(">>> " + str(part_img_url)) #print(">>> " + str(part_img_url))
print(str(e)) print(str(e))
# >>>>>>>>
progress(count, total_parts,'Adding minifig inventory to database')
cursor.execute('''INSERT INTO inventory ( cursor.execute('''INSERT INTO inventory (
set_num, set_num,
id, id,
@ -313,11 +352,15 @@ def new_set(set_num):
conn.commit() conn.commit()
conn.close() conn.close()
print('End Count: ' + str(count)) # >>>>>>>>
print('End Total: ' + str(total_parts)) progress(count, total_parts,'Closing database')
#print('End Count: ' + str(count))
#print('End Total: ' + str(total_parts))
count = total_parts count = total_parts
socketio.emit('update_progress', {'progress': int(count/total_parts*100)}, namespace='/progress')
# >>>>>>>>
progress(count, total_parts,'Cleaning up')
count = 0 count = 0
socketio.emit('task_completed', namespace='/progress') socketio.emit('task_completed', namespace='/progress')

View File

@ -38,6 +38,8 @@
<input class="input" type="text" id="inputField" name="inputField"> <input class="input" type="text" id="inputField" name="inputField">
</div> </div>
</div> </div>
<span id="progress-bar-text" style="left: 50%; font-size: 12px;"></span>
<progress id="progress-bar" class="progress is-large is-primary" value="0" max="100"> <progress id="progress-bar" class="progress is-large is-primary" value="0" max="100">
</progress> </progress>
<div class="field"> <div class="field">
@ -66,7 +68,7 @@
<section class="modal-card-body"> <section class="modal-card-body">
Set number does not exists: Set number does not exists:
<br> <br>
<b>{{ error }}</b> <b id="error-code"></b>
</section> </section>
<footer class="modal-card-foot"> <footer class="modal-card-foot">
<div class="buttons"> <div class="buttons">
@ -80,77 +82,83 @@
<script> <script>
var socket = io.connect('http://' + document.domain + ':' + location.port + '/progress'); var socket = io.connect('http://' + document.domain + ':' + location.port + '/progress');
// Event listener for receiving progress updates // Event listener for receiving progress updates
socket.on('update_progress', function(msg) { socket.on('update_progress', function (msg) {
var progress = msg.progress; var progress = msg.progress;
// document.getElementById("progress-bar").style.width = progress + "%"; var state = msg.desc;
document.getElementById("progress-bar").value = progress; console.log(progress,state);
document.getElementById("progress-bar").innerText = progress + "%"; // document.getElementById("progress-bar").style.width = progress + "%";
}); document.getElementById("progress-bar").value = progress;
document.getElementById("progress-bar").innerText = progress + "%";
document.getElementById("progress-bar-text").innerText = state;
});
// Event listener for the form submission // Event listener for the form submission
document.getElementById("createForm").addEventListener("submit", function(event) { document.getElementById("createForm").addEventListener("submit", function (event) {
event.preventDefault(); // Prevent default form submission event.preventDefault(); // Prevent default form submission
var inputField = document.getElementById("inputField").value; var inputField = document.getElementById("inputField").value;
socket.emit('start_task', { inputField: inputField }); // Emit socket event with inputField value socket.emit('start_task', { inputField: inputField }); // Emit socket event with inputField value
}); });
// Event listener for the 'task_completed' event // Event listener for the 'task_completed' event
socket.on('task_completed', function() { socket.on('task_completed', function () {
// Redirect to '/' // Redirect to '/'
window.location.href = '/'; document.getElementById("progress-bar-text").innerText = '';
});
socket.on('task_failed', function(data) { window.location.href = '/';
// Redirect to '/' });
const error = data.error;
document.getElementById('modal-js').style.display = 'block'; socket.on('task_failed', function () {
// window.location.href = '/create'; // Redirect to '/'
}); var inputField = document.getElementById("inputField").value;
console.log(inputField);
document.getElementById("modal-js").click();
document.getElementById("error-code").innerHTML = inputField;
document.getElementById("inputField").value = "";
// window.location.href = '/create';
});
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
window.onload = function () {
document.getElementById("modal-js").click(); };
// Functions to open and close a modal // Functions to open and close a modal
function openModal($el) { function openModal($el) {
$el.classList.add('is-active'); $el.classList.add('is-active');
} }
function closeModal($el) { function closeModal($el) {
$el.classList.remove('is-active'); $el.classList.remove('is-active');
} }
function closeAllModals() { function closeAllModals() {
(document.querySelectorAll('.modal') || []).forEach(($modal) => { (document.querySelectorAll('.modal') || []).forEach(($modal) => {
closeModal($modal); closeModal($modal);
}); });
} }
// Add a click event on buttons to open a specific modal // Add a click event on buttons to open a specific modal
(document.querySelectorAll('.js-modal-trigger') || []).forEach(($trigger) => { (document.querySelectorAll('.js-modal-trigger') || []).forEach(($trigger) => {
const modal = $trigger.dataset.target; const modal = $trigger.dataset.target;
const $target = document.getElementById(modal); const $target = document.getElementById(modal);
$trigger.addEventListener('click', () => { $trigger.addEventListener('click', () => {
openModal($target); openModal($target);
}); });
}); });
// Add a click event on various child elements to close the parent modal // Add a click event on various child elements to close the parent modal
(document.querySelectorAll('.modal-background, .modal-close, .modal-card-head .delete, .modal-card-foot .button') || []).forEach(($close) => { (document.querySelectorAll('.modal-background, .modal-close, .modal-card-head .delete, .modal-card-foot .button') || []).forEach(($close) => {
const $target = $close.closest('.modal'); const $target = $close.closest('.modal');
$close.addEventListener('click', () => { $close.addEventListener('click', () => {
closeModal($target); closeModal($target);
}); });
}); });
// Add a keyboard event to close all modals // Add a keyboard event to close all modals
document.addEventListener('keydown', (event) => { document.addEventListener('keydown', (event) => {
if(event.key === "Escape") { if (event.key === "Escape") {
closeAllModals(); closeAllModals();
} }
}); });