File size: 2,431 Bytes
b0b78da
 
 
 
 
67b352c
b0b78da
 
 
59bb2e3
 
b0b78da
 
866fc85
 
 
 
 
 
3130226
866fc85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8672afb
866fc85
8672afb
 
866fc85
 
 
 
 
0aa1af3
3130226
866fc85
b0b78da
79717c8
8672afb
 
b0b78da
d881552
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
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)