Rahatara commited on
Commit
f6fa516
1 Parent(s): dd312cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -131
app.py CHANGED
@@ -1,131 +1,62 @@
1
- import gradio as gr
2
- import replicate
3
- import os
4
- from huggingface_hub import InferenceClient
5
- import random
6
- import openai
7
-
8
- # Set API tokens
9
- os.environ["REPLICATE_API_TOKEN"] = "r8_8TlgofGX8rjeBL28vn0VBR93CWOUfvg4NbLS0"
10
- # Initialize the Replicate client
11
- rep_client = replicate.Client()
12
-
13
- # Set your OpenAI API key
14
- OPENAI_API_KEY = "sk-proj-5iy4bwrqAW8GpguiEawaT3BlbkFJ8p88lLSjOCeDbxWsAOlr"
15
- openai.api_key = OPENAI_API_KEY
16
- # Initialize the Replicate client
17
- rep_client = replicate.Client()
18
-
19
- # Predefined prompts for the dropdown
20
- predefined_prompts = [
21
- "Missing bolts on railway track",
22
- "Cracks on railway track",
23
- "Overgrown vegetation near railway track",
24
- "Broken railings on railway bridge",
25
- "Debris on railway track",
26
- "Damaged railway platform"
27
- ]
28
-
29
-
30
- def ask_rail_defect_question(question, model_name='ft:gpt-3.5-turbo-0125:personal::99NsSAeQ'):
31
- openai.api_key = OPENAI_API_KEY
32
- response = openai.ChatCompletion.create(
33
- model=model_name,
34
- messages=[
35
- {
36
- "role": "system",
37
- "content": "The assistant is knowledgeable about rail defects and can answer questions related to them.",
38
- },
39
- {
40
- "role": "user",
41
- "content": question,
42
- }
43
- ],
44
- )
45
- return response.choices[0].message['content']
46
-
47
- # Function to generate variations enhanced by the GPT model
48
- def generate_variations(base_prompt, number_of_variations):
49
- locations = ["on the left side", "on the right side", "at the top", "at the bottom", "in the center"]
50
- sizes = ["small", "medium", "large", "tiny", "huge"]
51
- weather_conditions = ["under cold conditions", "during hot weather", "in dry weather", "in humid conditions", "under varying temperatures"]
52
-
53
- variations = []
54
- for _ in range(number_of_variations):
55
- location = random.choice(locations)
56
- size = random.choice(sizes)
57
- weather = random.choice(weather_conditions)
58
-
59
- # Enhance the base prompt with the GPT model
60
- enhanced_prompt = ask_rail_defect_question(base_prompt)
61
-
62
- full_prompt = f"{enhanced_prompt}, with a {size} defect {location}, observed {weather}."
63
- variations.append(full_prompt)
64
- return variations
65
-
66
- # Function to generate images from prompts
67
- def generate_images(prompts):
68
- images = []
69
- for prompt in prompts:
70
- try:
71
- prediction = rep_client.predictions.create(
72
- version="ac732df83cea7fff18b8472768c88ad041fa750ff7682a21affe81863cbe77e4",
73
- input={"prompt": prompt, "scheduler": "K_EULER"}
74
- )
75
- prediction.wait()
76
- if prediction.status == "succeeded" and prediction.output:
77
- images.append(prediction.output[0])
78
- else:
79
- images.append("Failed to generate image.")
80
- except Exception as e:
81
- images.append(f"Error: {str(e)}")
82
- return images
83
-
84
- def process_railway_defects(prompt, number_of_images):
85
- variations = generate_variations(prompt, number_of_images)
86
- images = generate_images(variations)
87
- return images
88
-
89
-
90
-
91
- # UI creation
92
- with gr.Blocks() as app:
93
- with gr.Tabs("Prompt Input"):
94
- with gr.Tab("Current Defects"):
95
- with gr.Row():
96
- prompt_input = gr.Dropdown(choices=predefined_prompts, label="Select a prompt")
97
- number_input_dropdown = gr.Number(label="Number of images to generate", value=1, minimum=1, maximum=10)
98
- submit_button_dropdown = gr.Button("Generate")
99
- image_outputs_dropdown = gr.Gallery()
100
-
101
- def on_submit_click_dropdown(prompt, number_of_images):
102
- images = process_railway_defects(prompt, number_of_images)
103
- return images
104
-
105
-
106
-
107
- submit_button_dropdown.click(
108
- fn=on_submit_click_dropdown,
109
- inputs=[prompt_input, number_input_dropdown],
110
- outputs=image_outputs_dropdown
111
- )
112
-
113
- with gr.Tab("Custom Defect"):
114
- with gr.Row():
115
- custom_prompt_input = gr.Textbox(label="Custom Defect")
116
- number_input_custom = gr.Number(label="Number of images to generate", value=1, minimum=1, maximum=10)
117
- submit_button_custom = gr.Button("Generate")
118
- image_outputs_custom = gr.Gallery()
119
-
120
- def on_submit_click_custom(custom_prompt, number_of_images):
121
- images = process_railway_defects(custom_prompt, number_of_images)
122
- return images
123
-
124
- submit_button_custom.click(
125
- fn=on_submit_click_custom,
126
- inputs=[custom_prompt_input, number_input_custom],
127
- outputs=image_outputs_custom
128
- )
129
-
130
- if __name__ == "__main__":
131
- app.launch()
 
1
+ import streamlit as st
2
+ from PIL import Image, ImageEnhance, ImageOps
3
+ import numpy as np
4
+ import io
5
+ import zipfile
6
+
7
+ def apply_basic_augmentations(image):
8
+ """Applies basic augmentations such as rotation and color jitter."""
9
+ image = image.rotate(np.random.uniform(-30, 30))
10
+ enhancer = ImageEnhance.Color(image)
11
+ image = enhancer.enhance(np.random.uniform(0.75, 1.25))
12
+ if np.random.rand() > 0.5:
13
+ image = ImageOps.mirror(image)
14
+ return image
15
+
16
+ def simulate_latent_space_noising(image, noise_scale=25):
17
+ """Simulates latent space manipulation by adding noise."""
18
+ image_array = np.array(image)
19
+ noise = np.random.normal(0, noise_scale, image_array.shape)
20
+ noised_image_array = np.clip(image_array + noise, 0, 255).astype(np.uint8)
21
+ return Image.fromarray(noised_image_array)
22
+
23
+ def augment_image(image, augmentations_count):
24
+ """Generates augmented versions of a single image."""
25
+ augmented_images = []
26
+ for _ in range(augmentations_count):
27
+ augmented_image = apply_basic_augmentations(image)
28
+ augmented_image = simulate_latent_space_noising(augmented_image)
29
+ augmented_images.append(augmented_image)
30
+ return augmented_images
31
+
32
+ def create_downloadable_zip(augmented_images):
33
+ """Creates a ZIP file in memory for downloading."""
34
+ zip_buffer = io.BytesIO()
35
+ with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
36
+ for idx, image in enumerate(augmented_images):
37
+ img_byte_arr = io.BytesIO()
38
+ image.save(img_byte_arr, format="JPEG")
39
+ zip_file.writestr(f"augmented_image_{idx+1}.jpg", img_byte_arr.getvalue())
40
+ zip_buffer.seek(0)
41
+ return zip_buffer
42
+
43
+ st.title("Ready-To-Use Synthetic Image Dataset Generation with Few-shots")
44
+
45
+ uploaded_files = st.file_uploader("Choose images (1-10)", accept_multiple_files=True, type=["jpg", "jpeg", "png"])
46
+ augmentations_count = st.number_input("Number of augmented samples per image", min_value=1, max_value=10, value=3)
47
+
48
+ if uploaded_files:
49
+ all_augmented_images = []
50
+ for uploaded_file in uploaded_files:
51
+ image = Image.open(uploaded_file).convert("RGB")
52
+ augmented_images = augment_image(image, augmentations_count)
53
+ all_augmented_images.extend(augmented_images)
54
+
55
+ if st.button("Generate Synthetic Dataset") and all_augmented_images:
56
+ zip_buffer = create_downloadable_zip(all_augmented_images)
57
+ st.download_button(
58
+ label="Download ZIP",
59
+ data=zip_buffer,
60
+ file_name="augmented_images.zip",
61
+ mime="application/zip"
62
+ )