File size: 4,076 Bytes
7bf2f0d
 
 
 
 
 
 
 
 
 
51aa767
 
7bf2f0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51aa767
 
7bf2f0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51aa767
7bf2f0d
 
 
 
 
 
 
 
abda3d8
7bf2f0d
 
 
 
 
 
 
 
 
 
 
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# -*- coding: utf-8 -*-
"""Corrosion Excel.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1XTrJK3G8Har_yZt83wasZX1LYD6DG1Sa
"""

#install dependencies
#!pip install roboflow
#!pip install gradio

#import library
import gradio as gr
from roboflow import Roboflow
import numpy as np
from PIL import Image
import requests
from io import BytesIO
import pandas as pd
import os

# Initialize Roboflow with your API key
rf = Roboflow(api_key="kKDoCn3ABT9AKeFQDCB4")

# Function to calculate the area of a polygon using the shoelace formula
def calculate_polygon_area(points):
    n = len(points)
    area = 0.0
    for i in range(n):
        x1, y1 = points[i]
        x2, y2 = points[(i + 1) % n]
        area += (x1 * y2 - x2 * y1)
    return abs(area) / 2.0

# Function to process Roboflow prediction JSON and calculate corrosion areas
def calculate_corrosion_areas(json_data, unit="pixels", conversion_factor=1):
    corrosion_areas = []
    for prediction in json_data["predictions"]:
        if prediction["class"] == "Corrosion":
            points = [(point["x"], point["y"]) for point in prediction["points"]]
            area = calculate_polygon_area(points)
            if unit == "cm??":
                area *= conversion_factor  # Convert area from pixels to cm??
            corrosion_areas.append(area)

    total_corrosion_area = sum(corrosion_areas)

# Prepare output
    result = {
        "individual_areas": [f"{area} {unit}" for area in corrosion_areas],
        "total_area": f"{total_corrosion_area} {unit}",
        "recommendation": get_inspection_recommendation(total_corrosion_area)
    }
    return result

# Function to provide inspection recommendation based on total corrosion area
def get_inspection_recommendation(total_area):
    if total_area < 1000:
        return "No immediate inspection needed."
    elif total_area < 5000:
        return "Schedule an inspection in the next 6 months."
    else:
        return "Immediate inspection required."

# Define a Gradio interface to input a URL, run inference, and calculate corrosion areas
def url_infer_and_calculate(url, location, unit="pixels", conversion_factor=1):
    try:
        # Run inference using the Roboflow script
        rf_project = rf.workspace().project("corrosion-instance-segmentation-sfcpc")
        model = rf_project.version(3).model
        prediction = model.predict(url)

        # Ensure the response is properly formatted as JSON
        prediction_json = prediction.json()

        # Calculate corrosion areas from the Roboflow prediction
        corrosion_areas = calculate_corrosion_areas(prediction_json, unit, float(conversion_factor))

        # Download the image from the URL and convert it to a PIL Image
        response = requests.get(url)
        img = Image.open(BytesIO(response.content))

        # Create a pandas DataFrame for reporting
        df = pd.DataFrame([{'Number': index+1, 'URL': url, 'Location': location, 'corrosion_areas': corrosion_areas, 'Recommendation': corrosion_areas['recommendation']} for index in range(len(corrosion_areas))])

        # Write DataFrame to local CSV file with index included immediately after creating it.
        df.to_csv('Corrosion_Report.csv', index=False)

        return img, corrosion_areas, prediction_json

    except Exception as e:
        return {"error": str(e)}

# Create a Gradio interface for URL input, inference, and corrosion area calculation
iface = gr.Interface(
    fn=url_infer_and_calculate,
    inputs=[
      gr.inputs.Textbox(label="Enter the URL of an image"),
      gr.inputs.Textbox(label="Enter the Location"),
      gr.inputs.Dropdown(choices=["pixels", "cm??"], label="Area Unit"),
      gr.inputs.Textbox(label="Conversion Factor")
    ],
    outputs=[gr.outputs.Image(type="pil"), "json", "json"],
    title="Tim CCG",
    description="Enter the URL of an image to perform rust detection and calculate corrosion areas.",
)

# Launch the Gradio interface
iface.launch(debug=False, share=False)