File size: 2,193 Bytes
7a0ede7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
# coding: utf-8

# In[1]:


get_ipython().system('pip install gradio python-docx --quiet')


# In[2]:


import gradio as gr
import pandas as pd
import keras
import numpy as np
from docx import Document


# In[3]:


docs = []
model = keras.saving.load_model("resnet50_best.keras")


# In[4]:


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(label="Download report", visible=True)]


# In[5]:


# 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


# In[6]:


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)]


# In[7]:


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)
        d = gr.DownloadButton("Download report", visible=True)
    r = gr.DataFrame(headers=["Index", "File", "Result"])

    u.click(upload_images, f, [r, u, d])
    d.click(generate_docs, None, [u, d])


# In[8]:


demo.launch(share=True, debug=True)