| | import gradio as gr |
| | import numpy as np |
| | import tensorflow as tf |
| | from tensorflow.keras.models import load_model |
| | import os |
| |
|
| | |
| | model = load_model('model.keras') |
| |
|
| | |
| | try: |
| | with open('class_names.txt', 'r') as f: |
| | class_names = f.read().splitlines() |
| | except: |
| | |
| | num_classes = model.output_shape[-1] |
| | class_names = [f"Class {i}" for i in range(num_classes)] |
| |
|
| | |
| | def predict(image): |
| | """ |
| | Виконує передбачення класу за допомогою навченої моделі |
| | |
| | Args: |
| | image: Вхідне зображення |
| | |
| | Returns: |
| | dict: Словник з ймовірностями для кожного класу |
| | """ |
| | |
| | input_shape = model.input_shape[1:] |
| | |
| | |
| | if len(input_shape) == 3: |
| | |
| | resized_image = tf.image.resize(image, [input_shape[0], input_shape[1]]) |
| | |
| | |
| | if input_shape[2] == 1 and resized_image.shape[-1] == 3: |
| | resized_image = tf.image.rgb_to_grayscale(resized_image) |
| | |
| | |
| | img_array = tf.expand_dims(resized_image, 0) / 255.0 |
| | else: |
| | |
| | img_array = tf.reshape(image, (1, -1)) / 255.0 |
| | |
| | |
| | predictions = model.predict(img_array) |
| | |
| | |
| | result = {class_names[i]: float(predictions[0][i]) for i in range(len(class_names))} |
| | return result |
| |
|
| | |
| | interface = gr.Interface( |
| | fn=predict, |
| | inputs=gr.Image(), |
| | outputs=gr.Label(num_top_classes=len(class_names)), |
| | title="Модель багатокласової класифікації", |
| | description="Завантажте зображення для класифікації." |
| | ) |
| |
|
| | |
| | interface.launch() |
| |
|
| |
|