udayjawheri commited on
Commit
518144e
·
verified ·
1 Parent(s): 54e2390

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -45
app.py CHANGED
@@ -1,78 +1,83 @@
1
  import os
2
  import random
3
- import cv2
4
  import gradio as gr
5
  from PIL import Image
6
  import numpy as np
7
- from datasets import load_dataset
8
 
9
- def generate_and_delete_word_image(word):
10
- """Generates a combined image, displays it, and deletes it afterward.
 
 
 
 
 
11
  Args:
12
- word: The user-provided word (uppercase).
 
13
  Returns:
14
- The image data for displaying.
15
  """
 
 
 
 
 
16
 
17
- # Load the dataset
18
- dataset = load_dataset("udayjawheri/0-9_A-Z_Dataset")
19
-
20
- # Initialize an empty list to store the resized images
21
  resized_images = []
22
-
23
- # Iterate over each letter in the word
24
  for letter in word:
25
- # Get the corresponding folder for the letter
26
- letter_folder = dataset[letter]
27
 
28
- # Check if the folder exists
29
- if not letter_folder:
30
- print("Folder not found for the letter:", letter)
31
  continue
32
 
33
- # Get the list of images in the folder
34
- images_in_folder = list(letter_folder)
35
 
36
- # Check if there are any images in the folder
37
  if not images_in_folder:
38
- print("No images found for the letter:", letter)
39
  continue
40
 
41
- # Randomly select an image from the folder
42
- random_image = random.choice(images_in_folder)
43
-
44
- # Load the image using PIL, ensuring RGB mode
45
- image = Image.open(random_image).convert("RGB")
46
-
47
- # Resize the image to 250x250 pixels
48
- resized_image = np.array(image.resize((250, 250)))
 
 
 
 
 
 
 
49
 
50
- # Add the resized image to the list
51
  resized_images.append(resized_image)
52
 
53
- # Check if any images were found for the word
54
  if not resized_images:
55
  print("No images found for the input word.")
56
- return None
57
 
58
- # Concatenate the resized images horizontally
59
  concatenated_image = cv2.hconcat(resized_images)
60
 
61
- # Return the concatenated image
62
- return concatenated_image
63
 
64
  # Gradio interface with clear explanations
65
  interface = gr.Interface(
66
- fn=generate_and_delete_word_image,
67
  inputs="text", # User input for the word
68
- outputs="image", # Output as an image
69
- title="POCKET RANDOM NOTE GENERATOR", # Title
70
- description="Randsomator allows you to generate random ranson with one click.",
71
-
72
  css="""
73
- botton {
74
- background: green;
75
- color: #32B531
76
  }
77
  body {
78
  background-color: black;
@@ -83,8 +88,7 @@ interface = gr.Interface(
83
  margin-bottom: 10px;
84
  }
85
  """,
86
-
87
  )
88
 
89
-
90
  interface.launch(share=True)
 
1
  import os
2
  import random
 
3
  import gradio as gr
4
  from PIL import Image
5
  import numpy as np
 
6
 
7
+ import cv2
8
+
9
+
10
+ def generate_and_display_word_image(word):
11
+
12
+ """Generates a combined image using the Reticular method and displays it in a secure manner.
13
+
14
  Args:
15
+ word (str): The user-provided word (uppercase).
16
+
17
  Returns:
18
+ None: The function displays the image using Gradio and doesn't return a value.
19
  """
20
+
21
+ # Securely access dataset using environment variables (replace with actual names)
22
+ dataset_dir = os.getenv("udayjawheri/Random_Word_Genrator/dataset/")
23
+ if not dataset_dir:
24
+ raise ValueError("Environment variable WORD_IMAGE_DATASET_DIR not set!")
25
 
 
 
 
 
26
  resized_images = []
 
 
27
  for letter in word:
28
+ letter_folder_path = os.path.join(dataset_dir, letter)
 
29
 
30
+ # Validate folder existence to prevent potential path traversal attacks
31
+ if not os.path.isdir(letter_folder_path):
32
+ print(f"Folder not found for letter: {letter}")
33
  continue
34
 
35
+ images_in_folder = [img for img in os.listdir(letter_folder_path)
36
+ if img.endswith(".jpg") or img.endswith(".png")]
37
 
 
38
  if not images_in_folder:
39
+ print(f"No images found for letter: {letter}")
40
  continue
41
 
42
+ # Randomly select an image from the folder securely (prevent path traversal)
43
+ random_image_name = random.choice(images_in_folder)
44
+ validated_image_path = os.path.join(letter_folder_path, random_image_name)
45
+ # Check if the path falls within the expected dataset directory
46
+ if not validated_image_path.startswith(dataset_dir):
47
+ raise ValueError("Invalid image path detected!")
48
+
49
+ try:
50
+ # Load image using PIL, ensuring RGB mode
51
+ image = Image.open(validated_image_path).convert("RGB")
52
+ # Convert to NumPy array for OpenCV
53
+ resized_image = np.array(image.resize((250, 250)))
54
+ except Exception as e:
55
+ print(f"Error loading image: {e}")
56
+ continue
57
 
 
58
  resized_images.append(resized_image)
59
 
 
60
  if not resized_images:
61
  print("No images found for the input word.")
62
+ return
63
 
 
64
  concatenated_image = cv2.hconcat(resized_images)
65
 
66
+ # Display the concatenated image using Gradio (avoids saving/deleting)
67
+ interface.image = concatenated_image
68
 
69
  # Gradio interface with clear explanations
70
  interface = gr.Interface(
71
+ fn=generate_and_display_word_image,
72
  inputs="text", # User input for the word
73
+ outputs="image", # Output as an image displayed in Gradio
74
+ title="POCKET RANDOM NOTE GENERATOR", # Title
75
+ description="Generates random notes using letter images.",
76
+
77
  css="""
78
+ button {
79
+ background: green;
80
+ color: #32B531
81
  }
82
  body {
83
  background-color: black;
 
88
  margin-bottom: 10px;
89
  }
90
  """,
 
91
  )
92
 
93
+ # Launch the Gradio interface
94
  interface.launch(share=True)