import gradio as gr from pyzbar.pyzbar import decode from lambdas import upload_models, predict import base64 from io import BytesIO, StringIO from PIL import Image import pandas as pd import os.path DEBUG = True prefer_frontal_cam_html = """ """ config = {'possible_shifts': {'No shifts': 0}, 'possible_modes': ["waste"]} def login(username, password) -> bool: # TODO from username and password get restaurant_id if os.path.isfile('credentials.csv'): df = pd.read_csv('credentials.csv') else: s = os.environ.get('CREDENTIALS') df = pd.read_csv(StringIO(s)) if not len(df): return False for idx, row in df.iterrows(): if row['username'] == username and row['password'] == password: restaurant_id = int(row['restaurant_id']) restaurant_name = str(row['restaurant_name']) mode = 'waste' possible_modes = str(row.get('modes')).split(':') possible_shifts = {i.split(':')[0]: i.split(':')[1] for i in str(row.get('shifts')).split('-')} config_aux = {'restaurant_id': restaurant_id, 'restaurant_name': restaurant_name, 'mode': mode, 'possible_modes': possible_modes, 'possible_shifts': possible_shifts, } config.update(config_aux) return True return False def start_app(shift_id, mode): try: config_aux = {'shift_id': shift_id, 'mode': mode} config.update(config_aux) gr.Info('Loading models', ) status_code, r = upload_models(**config) if status_code in (201, 200, 204): gr.Info('Models Correctly Loaded. Ready to predict') else: raise gr.Error(f'Error loading the models: {r}') config.update(r) except Exception as e: raise gr.Error(f'Error Uploading the models. \n {e}') def predict_app(image, patient_id): buffered = BytesIO() image.save(buffered, format='JPEG') b64image = base64.b64encode(buffered.getvalue()).decode('utf-8') status_code, r = predict(b64image=b64image, patient_identifier=patient_id, **config) if status_code in (200, 201, 204): gr.Info('Prediction Successful') else: raise gr.Error(f'Error predicting {r}') # APP with gr.Blocks(head=prefer_frontal_cam_html) as block: with gr.Tab(label='Welcome'): gr.Markdown(f'# User: {config.get("restaurant_name", "Proppos")}') @gr.render() def render_dropdowns(): shift_dropdown = gr.Dropdown(label='Meal/Comida/Apat', value=list(config["possible_shifts"].items())[0], choices=tuple(config["possible_shifts"].items())) mode_dropdown = gr.Dropdown(label='Mode', value=config['possible_modes'][0], choices=config["possible_modes"]) start_button = gr.Button(value='START') start_button.click(fn=start_app, inputs=[shift_dropdown, mode_dropdown]) with gr.Tab(label='📷 Capture'): # MAIN TAB TO PREDICT gr.Markdown(f""" 1. Click to Access Webcam 2. """) im = gr.Image(sources=['webcam'], streaming=True, mirror_webcam=False, type='pil') with gr.Accordion(): eater_id = gr.Textbox(label='Patient Identification', placeholder='Searching Patient ID') current_eater_id = {'value': None} @gr.on(inputs=im, outputs=eater_id) def search_eater_id(image): d = decode(image) default_value = None current_value = current_eater_id['value'] or default_value new_value = d[0].data if d else default_value # If it is really a new value different from the default one, change it. final_value = new_value if new_value != default_value else current_value current_eater_id['value'] = final_value return final_value b = gr.Button('PRESS TO PREDICT') b.click(fn=predict_app, inputs=[im, eater_id], outputs=gr.Info()) with gr.Tab(label='â„šī¸ Status'): gr.Markdown(' Press the button to see the status of the Application and technical information') load_status_button = gr.Button('Load Status') status_json = gr.Json(label='Status') load_status_button.click(fn=lambda: config, outputs=status_json) with gr.Tab(label='📄 Documentation'): gr.Markdown() #block.launch(auth=("proppos", "Proppos2019")) block.launch(show_api=False, auth=login)