110 / app.py
kim1688's picture
Update app.py
79717c8 verified
import os
import numpy as np
import pandas as pd
import keras
import gradio as gr
from docx import Document
os.environ["KERAS_BACKEND"] = "tensorflow"
print("loading file")
docs = []
model = keras.saving.load_model("hf://kim1688/casting_defect_resnet50")
def upload_images(image_paths):
docs.clear()
df = pd.DataFrame(columns=["Index", "File", "Result"])
for i in range(len(image_paths)):
df.loc[i] = [str(i+1), image_paths[i].split("/")[-1], predict(image_paths[i])]
docs.append([str(i+1), image_paths[i].split("/")[-1], predict(image_paths[i])])
return [df, gr.Button(visible=True), gr.DownloadButton(visible=True), gr.DownloadButton(visible=False)]
# Function to preprocess image and predict
def predict(image_path):
img = keras.utils.load_img(image_path, target_size=(300, 300))
img_array = keras.utils.img_to_array(img)
img_array = keras.ops.expand_dims(img_array, 0)
prediction = model.predict(img_array)
class_names = ["Defective", "Ok"] # Class 0: def, Class 1: ok
predicted_class = class_names[1] if prediction > 0.5 else class_names[0]
return predicted_class
def generate_docs():
document = Document()
document.add_heading("Casting Report", 0)
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = "Index"
hdr_cells[1].text = "File"
hdr_cells[2].text = "Result"
for i in range(len(docs)):
row_cells = table.add_row().cells
row_cells[0].text = docs[i][0]
row_cells[1].text = docs[i][1]
row_cells[2].text = docs[i][2]
document.save("casting_report.docx")
return [gr.UploadButton(visible=True), gr.DownloadButton(visible=True), gr.DownloadButton(label=f"Download", value="casting_report.docx", visible=True)]
def download_file():
return [gr.UploadButton(visible=True), gr.DownloadButton(visible=True), gr.DownloadButton(visible=True)]
with gr.Blocks() as demo:
with gr.Column():
f = gr.File(file_count="multiple", file_types=[".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff"])
u = gr.Button("Upload files", visible=True)
d1 = gr.DownloadButton("Generate report", visible=True)
d2 = gr.DownloadButton("Download report", visible=False)
r = gr.DataFrame(headers=["Index", "File", "Result"])
u.click(upload_images, f, [r, u, d1, d2])
d1.click(generate_docs, None, [u, d1, d2])
d2.click(download_file, None, [u, d1, d2])
demo.launch(share=True, debug=True)