Adonai Vera commited on
Commit
5d18012
·
1 Parent(s): 06d5653

Get feedback from user and save image

Browse files
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
README 3.md DELETED
@@ -1,12 +0,0 @@
1
- ---
2
- title: Ofwat Defects Classification Demo
3
- emoji: 😻
4
- colorFrom: gray
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 4.7.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -2,12 +2,45 @@ import gradio as gr
2
  from transformers import pipeline
3
  from PIL import Image
4
  import os
 
 
 
 
5
 
6
  # Initialize the pipeline with your model
7
  pipe = pipeline("image-classification", model="SubterraAI/ofwat_cleaner_classification")
8
- HF_TOKEN = os.environ.get('HF_TOKEN')
9
- print(HF_TOKEN)
10
- hf_writer = gr.HuggingFaceDatasetSaver(HF_TOKEN, "SubterraAI/ofwat_cleaner_loop", separate_dirs=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  def classify_image(image):
13
  # Convert the input image to PIL format
@@ -19,23 +52,41 @@ def classify_image(image):
19
  # Extract labels and scores
20
  return {dic["label"]: dic["score"] for dic in res}
21
 
22
- # Create the Gradio interface
23
- iface = gr.Interface(
24
- classify_image,
25
- "image",
26
- "label",
27
- examples=[
28
- ["examples/CS.jpg"],
29
- ["examples/GI.jpg"],
30
- ["examples/PP.jpg"]
31
- ],
32
- description="Upload an image to view a classification demonstration leveraging the dataset/library of images collected by WRc & Unitied Utitlies during The Water Services Regulation Authority (OFWAT) Innovation Challenge – Artificial Intelligence and Sewers. Not only can you see the initial classification, but you as the user can also inform us if the classification is correct. Your response will be used to retrain this model. The team at Subterra would like to thank all of those involved in collecting this dataset as we hope that other groups will use it to further advance technology solutions for the water industry.",
33
- title="Sewer Obstruction Classification with AI by Subterra",
34
- allow_flagging="manual",
35
- flagging_options=["obstruction", "no_obstruction"],
36
- flagging_callback=hf_writer
37
-
38
- )
39
-
40
- # Launch the interface
41
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from transformers import pipeline
3
  from PIL import Image
4
  import os
5
+ from huggingface_hub import HfApi, upload_file
6
+ import io
7
+ import numpy as np
8
+ import uuid
9
 
10
  # Initialize the pipeline with your model
11
  pipe = pipeline("image-classification", model="SubterraAI/ofwat_cleaner_classification")
12
+ HF_TOKEN = os.getenv('HF_TOKEN')
13
+ DATASET_NAME = "SubterraAI/ofwat_cleaner_loop"
14
+ hf_api = HfApi()
15
+
16
+ # Directory where the flagged images will be saved
17
+ flagged_data_dir = "./flagged_data"
18
+
19
+ def simple_flag(image, label):
20
+ # Convert the input image to PIL format and save to a BytesIO object
21
+ pil_image = Image.fromarray(image.astype(np.uint8))
22
+ img_byte_arr = io.BytesIO()
23
+ pil_image.save(img_byte_arr, format='PNG')
24
+
25
+ # Generate a unique ID for the image
26
+ unique_id = str(uuid.uuid4())
27
+ img_filename = f"{unique_id}.png"
28
+
29
+ # Save the image to a BytesIO object
30
+ image_bytes = img_byte_arr.getvalue()
31
+
32
+ # Upload the image to the correct label directory in the Hugging Face dataset
33
+ label_dir = f"{label}/{img_filename}"
34
+ upload_file(
35
+ path_or_fileobj=io.BytesIO(image_bytes),
36
+ path_in_repo=label_dir,
37
+ repo_id=DATASET_NAME,
38
+ repo_type="dataset",
39
+ token=HF_TOKEN,
40
+ commit_message=f"Add image with label {label}"
41
+ )
42
+
43
+ return "Image saved successfully to Hugging Face dataset."
44
 
45
  def classify_image(image):
46
  # Convert the input image to PIL format
 
52
  # Extract labels and scores
53
  return {dic["label"]: dic["score"] for dic in res}
54
 
55
+ def save_flagged_image(image, label):
56
+ try:
57
+ # Convert the input image to PIL format
58
+ PIL_image = Image.fromarray(image).convert('RGB')
59
+
60
+ # Create the directory for the label if it doesn't exist
61
+ label_dir = os.path.join(flagged_data_dir, label)
62
+ os.makedirs(label_dir, exist_ok=True)
63
+
64
+ # Save the image with a unique filename
65
+ img_filename = f"{label}_{hash(image.tobytes())}.png"
66
+ img_path = os.path.join(label_dir, img_filename)
67
+ PIL_image.save(img_path)
68
+
69
+ return "Image saved successfully."
70
+ except Exception as e:
71
+ print(f"Error during flagging: {e}")
72
+ return f"An error occurred: {e}"
73
+
74
+ with gr.Blocks() as demo:
75
+ gr.Markdown("# Sewer Obstruction Classification with AI by Subterra")
76
+ gr.Markdown("Upload an image to view a classification demonstration leveraging the dataset/library of images collected by WRc & United Utilities during The Water Services Regulation Authority (OFWAT) Innovation Challenge – Artificial Intelligence and Sewers. Not only can you see the initial classification, but you as the user can also inform us if the classification is correct. Your response will be used to retrain this model. The team at Subterra would like to thank all of those involved in collecting this dataset as we hope that other groups will use it to further advance technology solutions for the water industry.")
77
+
78
+ with gr.Row():
79
+ with gr.Column():
80
+ img_input = gr.Image()
81
+ submit_button = gr.Button("Classify")
82
+ examples = gr.Examples(["examples/CS.jpg", "examples/GI.jpg", "examples/PP.jpg"], inputs=img_input)
83
+ with gr.Column():
84
+ output_label = gr.Label()
85
+ flagging_options = gr.Radio(["obstruction", "no_obstruction"])
86
+ flag_button = gr.Button("Flag")
87
+ flag_status = gr.Textbox(visible=True)
88
+
89
+ submit_button.click(classify_image, inputs=img_input, outputs=output_label)
90
+ flag_button.click(simple_flag, inputs=[img_input, flagging_options], outputs=flag_status)
91
+
92
+ demo.launch()
app_save.py DELETED
@@ -1,50 +0,0 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
- from PIL import Image
4
- import os
5
-
6
- # Initialize the pipeline with your model
7
- pipe = pipeline("image-classification", model="SubterraAI/ofwat_cleaner_classification")
8
- HF_TOKEN = os.environ.get('HF_TOKEN')
9
- hf_writer = gr.HuggingFaceDatasetSaver(HF_TOKEN, dataset_name="ofwat_cleaner_loop", private=True, separate_dirs=True)
10
-
11
- def classify_image(image):
12
- # Convert the input image to PIL format
13
- PIL_image = Image.fromarray(image).convert('RGB')
14
-
15
- # Classify the image using the pipeline
16
- res = pipe(PIL_image)
17
-
18
- # Extract labels and scores
19
- return {dic["label"]: dic["score"] for dic in res}
20
-
21
- def flag_feedback(image, option, flag_status):
22
- # Perform flagging action here using hf_writer
23
- hf_writer.flag((image, option))
24
-
25
- # Update the flag status to indicate feedback has been submitted
26
- flag_status.update("Feedback submitted. Thank you!")
27
- return flag_status
28
-
29
- # Create a state variable for the flag status
30
- flag_status = gr.State("")
31
-
32
- # Create the Gradio interface
33
- iface = gr.Interface(
34
- classify_image,
35
- inputs=[gr.Image(), gr.Radio(["obstruction", "no_obstruction"])],
36
- outputs=[gr.Label(), gr.Textbox(label="Flag Status", value=flag_status)],
37
- examples=[
38
- ["examples/CS.jpg"],
39
- ["examples/GI.jpg"],
40
- ["examples/PP.jpg"]
41
- ],
42
- description="Upload an image to view a classification demonstration...",
43
- title="Sewer Obstruction Classification with AI by Subterra",
44
- allow_flagging="manual",
45
- flagging_options=["obstruction", "no_obstruction"],
46
- flagging_callback=lambda image, option: flag_feedback(image, option, flag_status)
47
- )
48
-
49
- # Launch the interface
50
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
flagged/image/d97b9ae054eab1bd10dc/PP.jpg DELETED
Binary file (23.4 kB)
 
flagged/log.csv DELETED
@@ -1,8 +0,0 @@
1
- image,output 0,output 1,flag,username,timestamp
2
- "{""path"":""flagged/image/d97b9ae054eab1bd10dc/PP.jpg"",""url"":""http://127.0.0.1:7860/file=/private/var/folders/5q/yl8pmxm116g6r3k8fd9gk74m0000gn/T/gradio/12885a897d79141c54ccb542582449159242eaa0/PP.jpg"",""size"":null,""orig_name"":""PP.jpg"",""mime_type"":null}","{""label"":""VC"",""confidences"":[{""label"":""VC"",""confidence"":0.7706952691078186},{""label"":""PVC"",""confidence"":0.20648105442523956},{""label"":""PE"",""confidence"":0.005161861423403025},{""label"":""PF"",""confidence"":0.004196972120553255},{""label"":""CO"",""confidence"":0.0034184197429567575}]}","| Prefix | Full Name |
3
- | ------ | --------- |
4
- | CS | Carbon Steel |
5
- | GI | Galvanized Iron |
6
- | PP | Polypropylene |
7
- | RC | Reinforced Concrete |",,,2023-11-27 15:26:38.548865
8
- "{""path"":""flagged/image/f38c599fa2de8d03404c/RC.jpg"",""url"":""http://127.0.0.1:7860/file=/private/var/folders/5q/yl8pmxm116g6r3k8fd9gk74m0000gn/T/gradio/6ab5f5d1df06303f856175903bbfc4639d4780b3/RC.jpg"",""size"":null,""orig_name"":""RC.jpg"",""mime_type"":null}","{""label"":""obstruction"",""confidences"":[{""label"":""obstruction"",""confidence"":0.988347589969635},{""label"":""no_obstruction"",""confidence"":0.01165243424475193}]}",obstruction,,2024-01-09 12:23:43.084607
 
 
 
 
 
 
 
 
 
unit_test.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ HF_TOKEN = os.environ.get('HF_TOKEN')
4
+ hf_writer = gr.HuggingFaceDatasetSaver(HF_TOKEN, "image-classification-mistakes")
5
+ def image_classifier(inp):
6
+ return {'cat': 0.3, 'dog': 0.7}
7
+ demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
8
+ allow_flagging="manual", flagging_callback=hf_writer)
9
+
10
+ # Launch the interface
11
+ demo.launch()