File size: 4,237 Bytes
c541fe0
f20a02b
bef9af6
7d68714
 
 
bef9af6
 
 
6c9bc25
bef9af6
 
c541fe0
59f9511
 
 
 
 
 
 
 
 
 
 
 
 
 
7d68714
 
 
59f9511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c9bc25
 
c541fe0
113b3af
 
 
6c9bc25
 
 
 
 
113b3af
6c9bc25
113b3af
 
 
 
 
 
 
 
 
 
bdc0c73
6c9bc25
c541fe0
113b3af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c9bc25
bdc0c73
113b3af
 
 
 
 
 
 
 
 
 
 
bdc0c73
6c9bc25
8616add
59f9511
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
import gradio as gr
import time
import logging
import threading
import uuid


# Set up logging
logging.basicConfig(
    level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

def load_model(model_path):
    logger.info(f"Attempting to load model from {model_path}...")
    try:
        demo = gr.load(model_path)
        logger.info(f"Successfully loaded demo from {model_path}.")
        return demo
    except Exception as e:
        logger.error(f"Failed to load demo from {model_path}: {e}")
        return None

# Load the demo
demo = load_model("models/John6666/lustify-sdxl-nsfwsfw-v2-sdxl")

def generate_image(prompt, max_retries=5):
    call_id = uuid.uuid4()
    thread_id = threading.get_ident()
    logger.info(f"Call ID: {call_id}, Thread ID: {thread_id}, Attempt 1: Starting image generation with prompt: {prompt}")
    if demo is None:
        return None, "Error: Demo failed to load."

    for attempt in range(max_retries):
        try:
            logger.info(f"Attempt {attempt + 1}: Starting image generation with prompt: {prompt}")
            start_time = time.time()
            result = demo(prompt)
            generation_time = time.time() - start_time
            logger.info(f"Generation completed in {generation_time:.2f} seconds")
            logger.info(result)
            return result, f"Image generated successfully\nGeneration time: {generation_time:.2f} seconds"
        except Exception as e:
            logger.error(f"Error on attempt {attempt + 1}: {str(e)}")
            if attempt < max_retries - 1:
                logger.info(f"Retrying... ({attempt + 2}/{max_retries})")
            else:
                logger.error("Max retries reached. Giving up.")
                return None, f"Failed to generate image after {max_retries} attempts. Last error: {str(e)}"
    
    # This line should never be reached, but just in case:
    return None, "Unexpected error occurred"

# Set the root directory as a reusable variable
ROOT_DIR = "./tmp"

# Set a password for file explorer access
FILE_EXPLORER_PASSWORD = "secret123"  # You should use a more secure password in a real application

def show_image(file_path):
    logger.info(f"show_image function called with file_path: {file_path}")
    if file_path:
        result = file_path[0] if isinstance(file_path, list) else file_path
        logger.info(f"Returning file path: {result}")
        return result, f"Selected image: {result}"
    logger.warning("No file path provided")
    return None, "No image selected"

def check_seed(seed):
    logger.info("Seed check initiated")
    if seed == FILE_EXPLORER_PASSWORD:
        logger.info("Correct seed entered")
        return gr.update(visible=True)
    else:
        logger.info("Incorrect seed entered")
        return gr.update(visible=False)

logger.info("Starting Gradio app")
with gr.Blocks() as demo:
    gr.Markdown("# Text-to-Image Generation and File Explorer")
    gr.Markdown("Enter a prompt to generate an image or enter the correct seed to access additional features.")

    with gr.Row():
        with gr.Column(scale=1):
            prompt_input = gr.Textbox(label="Enter your prompt")
            seed_input = gr.Textbox(label="Enter seed", type="password")
            generate_button = gr.Button("Generate Image")

            file_explorer = gr.FileExplorer(
                glob="**/*.webp",
                file_count="single",
                root_dir=ROOT_DIR,
                label="Select a WebP image",
                visible=False
            )
            output_info = gr.Textbox(label="Output Information", lines=3)

        with gr.Column(scale=2):
            shared_image = gr.Image(label="Image Display")

    # Set up event handlers
    generate_button.click(
        generate_image,
        inputs=prompt_input,
        outputs=[shared_image, output_info]
    )

    seed_input.change(
        check_seed,
        inputs=seed_input,
        outputs=file_explorer
    )

    file_explorer.change(
        show_image,
        inputs=file_explorer,
        outputs=[shared_image, output_info]
    )

logger.info("Launching Gradio app")
demo.launch(max_threads=1)
logger.info("Gradio app launched")