Spaces:
Running
Running
| import gradio as gr | |
| import cv2 | |
| from pyzbar.pyzbar import decode | |
| import requests | |
| import json | |
| from PIL import Image | |
| import numpy as np | |
| import os | |
| import gradio as gr | |
| from tensorflow.keras.models import load_model | |
| from tensorflow.keras.preprocessing import image | |
| from tensorflow.keras.applications.mobilenet_v2 import preprocess_input | |
| import numpy as np | |
| # Load the pre-trained model | |
| model = load_model('model.h5') | |
| # Class index to category name mapping | |
| class_names = { | |
| 0: 'Air_Conditioners', | |
| 1: 'Coffee_Espresso_Machines', | |
| 2: 'Computer_Monitors', | |
| 3: 'Televisions', | |
| 4: 'Ironing', | |
| 5: 'Televisions', | |
| 6: 'Vacuums' | |
| } | |
| # Category to tips mapping | |
| tips = { | |
| "Air_Conditioners": [ | |
| "Set the thermostat to a higher temperature when you're not at home.", | |
| "Use ceiling fans to circulate air; this allows you to raise the thermostat setting by about 4°F with no reduction in comfort.", | |
| "Regularly clean or replace air filters to maintain efficiency and performance of the air conditioning system." | |
| ], | |
| "Coffee_Espresso_Machines": [ | |
| "Turn off the machine when not in use, especially those that heat water continuously.", | |
| "Use a manual or programmable coffee maker that can be scheduled to turn on only when you need coffee and turn off immediately after.", | |
| "Preheat your cup with hot water from the tap to avoid using extra energy to heat the cup with the machine." | |
| ], | |
| "Computer_Monitors": [ | |
| "Turn off the monitor when not in use to save energy.", | |
| "Adjust the brightness settings to lower levels which can significantly reduce power consumption.", | |
| "Use energy-saving modes like sleep or hibernate which minimize energy use when the monitor is not actively being used." | |
| ], | |
| "Ironing": [ | |
| "Use the iron’s steam function to reduce ironing time by efficiently removing wrinkles.", | |
| "Iron large batches of clothing at once to avoid reheating the iron multiple times.", | |
| "Turn off the iron a few minutes before finishing, using the residual heat to complete your ironing." | |
| ], | |
| "Televisions": [ | |
| "Turn off the TV when not in use.", | |
| "Adjust the brightness to a lower, comfortable level.", | |
| "Use a smart power strip to prevent phantom energy drain." | |
| ], | |
| "Vacuums": [ | |
| "Keep the vacuum filters and brushes clean to maintain suction and efficiency.", | |
| "Use the appropriate settings and attachments for different types of flooring to optimize suction and reduce time spent vacuuming.", | |
| "Vacuum multiple rooms in a sequence to avoid frequent starts and stops that increase energy usage." | |
| ] | |
| } | |
| def read_barcode(image): | |
| pil_image = Image.fromarray(image) | |
| decoded_objects = decode(pil_image) | |
| barcodes = [obj.data.decode("utf-8") for obj in decoded_objects] | |
| return barcodes[0] if barcodes else None | |
| def get_product_info(barcode): | |
| primary_api_key = "88ABB59A67B72D87CC80C7FAB80E6632" | |
| fallback_api_key = "0aj97xf02hji3h4wep2tlkldc98zf2" | |
| primary_url = f"https://api.upcdatabase.org/product/{barcode}?apikey={primary_api_key}" | |
| fallback_url = f"https://api.barcodelookup.com/v3/products?barcode={barcode}&formatted=y&key={fallback_api_key}" | |
| try: | |
| response = requests.get(primary_url) | |
| data=response.json() | |
| if response.status_code == 200 and data['success']: | |
| return (data,1) | |
| else: | |
| response = requests.get(fallback_url) | |
| return (response.json(),2) | |
| except: | |
| return ({},0) | |
| def preprocess_image(img): | |
| img = image.img_to_array(img) | |
| img = image.smart_resize(img, (150, 150)) # Resizing the image to the required dimensions | |
| img = np.expand_dims(img, axis=0) | |
| return preprocess_input(img) | |
| def predict_image(img): | |
| processed_image = preprocess_image(img) | |
| prediction = model.predict(processed_image) | |
| predicted_class_index = np.argmax(prediction, axis=1)[0] | |
| predicted_class_name = class_names[predicted_class_index] | |
| tips_text = "\n".join(tips[predicted_class_name]) | |
| return predicted_class_index,predicted_class_name, tips_text | |
| def process_image(image): | |
| barcode = read_barcode(image) | |
| if barcode: | |
| product_info,API = get_product_info(barcode) | |
| if product_info: | |
| if barcode=="0887276371375": | |
| energy_info = { | |
| "Energy_Characteristics": [ | |
| "Product meets ENERGY STAR guidelines for energy efficiency.", | |
| "Power management settings enabled by default, with timing settings from 1 minute to 5 hours.", | |
| "Device can wake up with a button press on the chassis from sleep mode." | |
| ], | |
| "Tips_to_Save_Energy": [ | |
| "Adjust the LCD brightness to reduce eye strain and save power.", | |
| "Use power management settings to enable power-saving mode when not in use or after set inactivity period.", | |
| "Fully charge the battery before using the computer for the first time to ensure optimal battery performance and longevity." | |
| ], | |
| "Energy_Consumption_Estimation_in_Different_Modes": [ | |
| "Power Saving Mode: Consumes minimal energy when LCD is closed or there is no input for a predetermined period.", | |
| "Battery Use: Higher energy consumption during battery charging, especially if the computer is used during charging.", | |
| "On/Off Modes: Energy consumption varies significantly between active use, sleep mode, and fully turned off, with sleep mode designed to save energy." | |
| ] | |
| } | |
| elif barcode=="0719192596764": | |
| energy_info = { | |
| "Energy_Characteristics": [ | |
| "Power Requirement: AC 100 - 240 V ~ 50 / 60 Hz.", | |
| "Current Value/Power Consumption varies by model (e.g., 0.9 A / 90 W for 40LF6300, 1.6 A / 160 W for 65LF6300).", | |
| "Product qualifies for ENERGY STAR in the factory default (Home Use) setting; altering factory default settings may increase power consumption beyond ENERGY STAR qualification." | |
| ], | |
| "Tips_to_Save_Energy": [ | |
| "Utilize the TV's energy-saving settings to reduce power consumption.", | |
| "Adjust the screen brightness to lower settings to save power.", | |
| "Ensure the TV is fully turned off and not in standby mode when not in use to minimize energy consumption." | |
| ], | |
| "Energy_Consumption_Estimation_in_Different_Modes": [ | |
| "Standby Mode: Minimal energy usage, but power is still consumed unless the device is fully unplugged.", | |
| "Active Mode (Energy Saving Mode On): Reduces power usage; specific power consumption values are lower than in normal operating mode.", | |
| "Active Mode (Normal): Consumption corresponds to the listed current values/power consumption figures depending on model and settings." | |
| ] | |
| } | |
| else: | |
| energy_info = {"Info":"Product information not found in our database"} | |
| data=product_info | |
| if API==1: | |
| data=data['title'] | |
| elif API==2: | |
| data=data["products"][0]["title"] | |
| return barcode, data, json.dumps(energy_info, indent=4) | |
| else: | |
| return barcode, "Product information not found", "{}" | |
| else: | |
| predicted_class_index,predicted_class_name,tips_text=predict_image(image) | |
| data = {"tips": tips_text} | |
| json_data = json.dumps(data, indent=4) | |
| return predicted_class_index, predicted_class_name, json_data | |
| interface = gr.Interface( | |
| fn=process_image, | |
| inputs=[gr.Image(type="numpy")], | |
| outputs=[gr.Textbox(label="Barcode/Index"), gr.Textbox(label="Product Information"), gr.JSON(label="Energy Info")] | |
| ) | |
| interface.launch(share=True) |