SilverDragon9 commited on
Commit
d74c5e6
Β·
verified Β·
1 Parent(s): e708547

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -36
app.py CHANGED
@@ -1,50 +1,83 @@
1
  import gradio as gr
2
- from PIL import Image
3
- import random
4
- import logging
5
  import os
 
 
6
  import joblib
7
 
8
- # === Setup Logging ===
9
- logging.basicConfig(
10
- level=logging.INFO,
11
- format="%(asctime)s - %(levelname)s - %(message)s",
12
- handlers=[
13
- logging.FileHandler("text_to_image.log"),
14
- logging.StreamHandler()
15
- ]
16
- )
17
-
18
- # === Load Model ===
19
- def load_model(model_path="fridge_model.pkl"):
 
 
 
 
 
 
 
 
 
 
20
  try:
21
- if not os.path.exists(model_path):
22
- raise FileNotFoundError(f"Model not found at: {model_path}")
23
- model = joblib.load(model_path)
24
- logging.info("βœ… Model loaded successfully.")
 
 
 
25
  return model
26
  except Exception as e:
27
- logging.error(f"❌ Failed to load model: {e}")
28
  return None
29
 
30
- # Dummy placeholder function (replace with actual inference)
31
- def dummy_text_to_image(prompt):
32
- logging.info(f"πŸ” Received prompt: {prompt}")
33
- img = Image.new("RGB", (256, 256), (
34
- random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
35
- )
36
- logging.info("πŸ–ΌοΈ Returning dummy image.")
37
- return img
38
-
39
  model = load_model()
40
 
41
- # === Gradio Interface ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
43
- gr.Markdown("## πŸ–ΌοΈ Text to Image Generator - Minimal (Light Mode)")
44
- prompt = gr.Textbox(placeholder="Enter your prompt here", label="Prompt")
45
- output = gr.Image(label="Generated Image", type="pil")
46
- generate = gr.Button("Generate")
 
 
 
 
 
 
 
47
 
48
- generate.click(fn=dummy_text_to_image, inputs=prompt, outputs=output)
49
 
50
- demo.launch()
 
 
1
  import gradio as gr
2
+ from PIL import Image, ImageDraw
 
 
3
  import os
4
+ import uuid
5
+ import logging
6
  import joblib
7
 
8
+ # ───── Configuration ───── #
9
+ OUTPUT_DIR = "outputs"
10
+ MODEL_PATH = "fridge_model.pkl" # Placeholder path
11
+
12
+ # ───── Setup ───── #
13
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # ───── Dummy Placeholder Model ───── #
18
+ # Replace this function with your actual model inference logic
19
+ def generate_image_from_text(prompt, model=None):
20
+ logger.info("Running placeholder image generator...")
21
+
22
+ # Create a simple white image with text overlay
23
+ image = Image.new("RGB", (512, 512), color="white")
24
+ draw = ImageDraw.Draw(image)
25
+ draw.text((10, 250), prompt, fill="black")
26
+ return image
27
+
28
+ # ───── Load Model ───── #
29
+ def load_model():
30
  try:
31
+ # Simulate model loading
32
+ if os.path.exists(MODEL_PATH):
33
+ model = joblib.load(MODEL_PATH)
34
+ logger.info("Model loaded successfully.")
35
+ else:
36
+ logger.warning(f"Model file not found at: {MODEL_PATH}. Using None.")
37
+ model = None
38
  return model
39
  except Exception as e:
40
+ logger.error(f"Failed to load model: {e}")
41
  return None
42
 
 
 
 
 
 
 
 
 
 
43
  model = load_model()
44
 
45
+ # ───── Prediction Wrapper ───── #
46
+ def predict(prompt):
47
+ try:
48
+ logger.info(f"Received prompt: {prompt}")
49
+ image = generate_image_from_text(prompt, model=model)
50
+
51
+ if not isinstance(image, Image.Image):
52
+ raise ValueError("Generated output is not a valid image.")
53
+
54
+ # Save the image for download
55
+ image_id = str(uuid.uuid4())
56
+ output_path = os.path.join(OUTPUT_DIR, f"{image_id}.png")
57
+ image.save(output_path)
58
+ logger.info(f"Image saved to: {output_path}")
59
+
60
+ return image, output_path
61
+
62
+ except Exception as e:
63
+ logger.error(f"Prediction error: {e}")
64
+ return None, None
65
+
66
+ # ───── Gradio UI ───── #
67
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
68
+ gr.Markdown("## πŸ–ΌοΈ Text-to-Image Generator (Minimal, Light Mode)")
69
+ with gr.Row():
70
+ prompt_input = gr.Textbox(label="Enter a text prompt", placeholder="e.g. A castle on a cloud at night")
71
+ with gr.Row():
72
+ generate_btn = gr.Button("Generate Image")
73
+ with gr.Row():
74
+ output_image = gr.Image(label="Generated Image")
75
+ download_button = gr.File(label="Download Image")
76
+
77
+ def run(prompt):
78
+ return predict(prompt)
79
 
80
+ generate_btn.click(fn=run, inputs=prompt_input, outputs=[output_image, download_button])
81
 
82
+ if __name__ == "__main__":
83
+ demo.launch()