Spaces:
Runtime error
Runtime error
| #!/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) | |