|
from keras.models import load_model |
|
from PIL import Image, ImageOps |
|
import numpy as np |
|
import gradio as gr |
|
import random |
|
|
|
|
|
model = load_model("keras_model.h5", compile=False) |
|
class_names = open("labels.txt", "r").readlines() |
|
|
|
|
|
temp = "" |
|
|
|
|
|
def evaluate_expression(expression): |
|
try: |
|
result = eval(expression) |
|
return str(result) |
|
except Exception as e: |
|
return f"エラー: {str(e)}" |
|
|
|
|
|
def generate_random_expression(): |
|
operators = ['+', '-', '*', '/'] |
|
num1 = random.randint(1, 9) |
|
num2 = random.randint(1, 9) |
|
operator = random.choice(operators) |
|
expression = f"{num1} {operator} {num2}" |
|
return expression |
|
|
|
|
|
def generate_valid_expression(): |
|
while True: |
|
true_answer = generate_random_expression() |
|
if len(evaluate_expression(true_answer)) == 1: |
|
return true_answer |
|
|
|
|
|
def display_question(): |
|
global temp |
|
question = generate_valid_expression() |
|
temp = question |
|
return question |
|
|
|
|
|
def greet(answer_img, question=display_question()): |
|
global temp |
|
|
|
user_answer_data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) |
|
user_answer_image = Image.fromarray(answer_img).convert('RGB') |
|
size = (224, 224) |
|
user_answer_image = ImageOps.fit(user_answer_image, size, Image.LANCZOS) |
|
user_answer_array = np.asarray(user_answer_image) |
|
user_normalized_image_array = (user_answer_array.astype(np.float32) / 127.0) - 1 |
|
user_answer_data[0] = user_normalized_image_array |
|
|
|
|
|
answer_prediction = model.predict(user_answer_data) |
|
predicted_number = class_names[np.argmax(answer_prediction)][2:] |
|
|
|
|
|
if int(predicted_number) == int(evaluate_expression(question)): |
|
result = f"正解! 画像認識で確認した数字: {predicted_number}, 正しい答え: {evaluate_expression(question)}" |
|
else: |
|
result = f"不正解! 画像認識で確認した数字: {predicted_number}, 正しい答え: {evaluate_expression(question)}" |
|
|
|
|
|
print(result) |
|
return result |
|
|
|
|
|
iface = gr.Interface( |
|
fn=greet, |
|
inputs=["image"], |
|
outputs=["text"], |
|
live=False, |
|
title="問題", |
|
description=temp |
|
) |
|
iface.launch(debug=True, share=True) |
|
|