File size: 3,280 Bytes
df1b115
 
28a8a18
 
 
 
df1b115
28a8a18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import pandas as pd
import gradio as gr
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import json
from ultralytics import YOLO


# ======================= МОДЕЛЬ ===================================

model = YOLO("yolov11m_best.pt")

# ================== ЧТЕНИЕ НАЗВАНИЙ И ЦЕН =======================

with open('Fruit_Veggies_Price.json', 'r', encoding='utf-8') as file:
    fruits_data = json.load(file)


# таблица с данными
detections = []


# =========================== ДЕТЕКЦИЯ ПЛОДА ============================

def detect_fruit(image, weight):
    results = model.predict(source=image, conf=0.5)
    detections = results[0].boxes.data.tolist()
    detected_fruit = None
    
    for det in detections:
        label = model.names[int(det[5])]  # название фрукта
        if label in fruits_data:
            detected_fruit = label
            break

    if not detected_fruit:
        return image, "Фрукт не обнаружен", None, None
    
    fruit_name = fruits_data[detected_fruit]["name"]
    price_per_kg = fruits_data[detected_fruit]["price_per_kg"]
    total_price = round(price_per_kg * weight, 2)
    
    return image, fruit_name, weight, total_price


# =========================== ЧЕК ============================

# функция для добавления позиции в чек
def create_receipt(fruit_name, weight, total_price):
    # белый фон для чека
    receipt_img = Image.new("RGB", (300, 200), color="white")
    draw = ImageDraw.Draw(receipt_img)
    
    # шрифт
    try:
        font = ImageFont.truetype("arial.ttf", 18)
    except IOError:
        font = ImageFont.load_default()
    
    # Записываем текст на чеке
    draw.text((10, 10), "Чек", fill="black", font=font)
    draw.text((10, 50), f"Продукт: {fruit_name}", fill="black", font=font)
    draw.text((10, 80), f"Вес: {weight} кг", fill="black", font=font)
    draw.text((10, 110), f"Цена за кг: {fruits_data[detected_fruit]['price_per_kg']} руб.", fill="black", font=font)
    draw.text((10, 140), f"Сумма: {total_price} руб.", fill="black", font=font)
    
    return receipt_img


# ======================= ИНТЕРФЕЙС ============================

def gradio_interface(image, weight):
    image, fruit_name, weight, total_price = detect_fruit(image, weight)
    if not fruit_name:
        return image, None  # Вернуть пустой чек
    
    receipt = create_receipt(fruit_name, weight, total_price)
    return image, receipt

image_input = gr.inputs.Image(label="Изображение с веб-камеры")
weight_input = gr.inputs.Number(label="Вес (кг)", default=1.0)
image_output = gr.outputs.Image(label="Распознанный фрукт")
receipt_output = gr.outputs.Image(label="Чек")

gr.Interface(
    fn=gradio_interface,
    inputs=[image_input, weight_input],
    outputs=[image_output, receipt_output],
    title="Определение фрукта и создание чека",
    description="Загрузите изображение фрукта на весах, введите вес и получите чек"
).launch()