awacke1 commited on
Commit
28ae035
·
verified ·
1 Parent(s): 8c34361

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -118
app.py CHANGED
@@ -1,132 +1,93 @@
1
  import streamlit as st
2
- import requests
3
- import base64
4
- from io import BytesIO
5
- from PIL import Image
6
- import time
7
 
8
  # Streamlit app title and description
9
- st.title("LoraTheExplorer Image Generation Wrapper")
10
  st.markdown("""
11
- This Streamlit app wraps the MultimodalArt LoraTheExplorer Gradio app to generate images from text prompts.
12
- Enter a prompt and adjust settings to create images. Note: Adjust settings based on the Gradio app's capabilities.
13
  """)
14
 
15
- # Backend URL of the Gradio app (assumed API endpoint)
16
- BACKEND_URL = "https://multimodalart-loratheexplorer.hf.space/api/predict/"
17
 
18
- # Placeholder style options (assuming a text-to-image model with style support)
19
- STYLE_OPTIONS = [
20
- "(No style)", "Cinematic", "Anime", "Digital Art", "Fantasy Art"
21
- ]
 
 
 
 
 
 
 
 
22
 
23
- # Function to apply style (generic, to be adjusted based on actual Gradio app)
24
- def apply_style(style_name, prompt, negative):
25
- style_dict = {
26
- "(No style)": ("{prompt}", ""),
27
- "Cinematic": (
28
- "cinematic still {prompt}, highly detailed, moody, epic",
29
- "blurry, low quality, cartoon"
30
- ),
31
- "Anime": (
32
- "anime artwork {prompt}, vibrant, studio anime, highly detailed",
33
- "photo, realism, blurry"
34
- ),
35
- "Digital Art": (
36
- "digital artwork {prompt}, illustrative, painterly, highly detailed",
37
- "photo, low quality"
38
- ),
39
- "Fantasy Art": (
40
- "fantasy concept art of {prompt}, ethereal, epic, magical",
41
- "realistic, blurry, text"
42
- )
43
- }
44
- positive, neg = style_dict.get(style_name, style_dict["(No style)"])
45
- return positive.replace("{prompt}", prompt), neg + (negative or "")
46
-
47
- # Function to call the Gradio backend
48
- def generate_images(prompt, negative_prompt, guidance_scale, style_name):
49
- try:
50
- # Apply style to prompt and negative prompt
51
- styled_prompt, styled_negative = apply_style(style_name, prompt, negative_prompt)
52
-
53
- # Prepare payload (based on typical Gradio API structure)
54
- payload = {
55
- "data": [
56
- styled_prompt,
57
- styled_negative,
58
- guidance_scale,
59
- style_name
60
- ]
61
- }
62
-
63
- # Send request to Gradio backend
64
- start_time = time.time()
65
- response = requests.post(BACKEND_URL, json=payload, timeout=60)
66
- elapsed_time = time.time() - start_time
67
 
68
- # Check response
69
- if response.status_code != 200:
70
- st.error(f"Error: Received status code {response.status_code}")
71
- return None
 
 
 
 
72
 
73
- # Parse response
74
- json_data = response.json()
75
- if "data" not in json_data or not json_data["data"]:
76
- st.error("Error: No images returned from the backend.")
77
- return None
 
 
78
 
79
- # Extract images (assuming base64 strings or URLs)
80
- images = []
81
- for img_data in json_data["data"]: # Adjust based on actual response
82
- if isinstance(img_data, str):
83
- if img_data.startswith("data:image"):
84
- img_base64 = img_data.split(",")[1]
85
- img_bytes = base64.b64decode(img_base64)
86
- img = Image.open(BytesIO(img_bytes))
87
- images.append(img)
88
- elif img_data.startswith("http"):
89
- response = requests.get(img_data, timeout=5)
90
- img = Image.open(BytesIO(response.content))
91
- images.append(img)
92
- else:
93
- st.warning(f"Unexpected image data format: {img_data}")
94
- else:
95
- st.warning("Unexpected image data type.")
96
 
97
- if images:
98
- st.success(f"Images generated in {elapsed_time:.2f} seconds!")
99
- return images
100
-
101
- except requests.exceptions.RequestException as e:
102
- st.error(f"Network error: {str(e)}")
103
- return None
104
- except ValueError as e:
105
- st.error(f"Error decoding response: {str(e)}")
106
- return None
107
- except Exception as e:
108
- st.error(f"Unexpected error: {str(e)}")
109
- return None
 
 
 
110
 
111
- # Streamlit UI components
112
- with st.form(key="input_form"):
113
- prompt = st.text_input("Enter your prompt", placeholder="A magical forest with glowing creatures")
114
- negative_prompt = st.text_input("Negative prompt (optional)", placeholder="blurry, low quality")
115
- guidance_scale = st.slider("Guidance Scale", min_value=0.0, max_value=50.0, value=7.5, step=0.1)
116
- style_name = st.selectbox("Image Style", options=STYLE_OPTIONS, index=0)
117
- submit_button = st.form_submit_button("Generate Images")
118
 
119
- # Handle form submission
120
- if submit_button:
121
- if not prompt:
122
- st.error("Please enter a prompt.")
123
- else:
124
- with st.spinner("Generating images..."):
125
- images = generate_images(prompt, negative_prompt, guidance_scale, style_name)
126
- if images:
127
- # Display images in a gallery
128
- st.subheader("Generated Images")
129
- cols = st.columns(min(len(images), 3))
130
- for idx, img in enumerate(images):
131
- with cols[idx % 3]:
132
- st.image(img, use_column_width=True)
 
1
  import streamlit as st
2
+ import streamlit.components.v1 as components
3
+ import urllib.parse
 
 
 
4
 
5
  # Streamlit app title and description
6
+ st.title("LoraTheExplorer Gradio App Wrapper")
7
  st.markdown("""
8
+ This Streamlit app embeds the MultimodalArt LoraTheExplorer Gradio app in an iframe.
9
+ Use the controls below to interact with the app or prefill prompts (if supported).
10
  """)
11
 
12
+ # Gradio app URL
13
+ GRADIO_URL = "https://multimodalart-loratheexplorer.hf.space"
14
 
15
+ # Function to generate iframe HTML
16
+ def render_gradio_iframe(url, width=850, height=600):
17
+ iframe_html = f"""
18
+ <iframe
19
+ src="{url}"
20
+ frameborder="0"
21
+ width="{width}"
22
+ height="{height}"
23
+ style="border: none;"
24
+ ></iframe>
25
+ """
26
+ return iframe_html
27
 
28
+ # Function to attempt to prefill prompt via URL parameters (if Gradio app supports it)
29
+ def generate_url_with_prompt(base_url, prompt):
30
+ # URL-encode the prompt
31
+ encoded_prompt = urllib.parse.quote(prompt)
32
+ # Append as a query parameter (assumption: Gradio app might accept ?prompt=...)
33
+ # This is speculative; adjust based on actual app behavior
34
+ return f"{base_url}?prompt={encoded_prompt}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ # Sidebar for controls
37
+ st.sidebar.header("Controls")
38
+ prompt = st.sidebar.text_input(
39
+ "Enter a prompt",
40
+ placeholder="A magical forest with glowing creatures",
41
+ help="Enter a prompt to prefill in the Gradio app (if supported)."
42
+ )
43
+ apply_prompt = st.sidebar.button("Apply Prompt")
44
 
45
+ # Handle prompt application
46
+ if apply_prompt and prompt:
47
+ # Attempt to modify URL with prompt
48
+ modified_url = generate_url_with_prompt(GRADIO_URL, prompt)
49
+ st.sidebar.info(f"Attempting to load with prompt: {prompt}")
50
+ else:
51
+ modified_url = GRADIO_URL
52
 
53
+ # Embed Gradio app
54
+ st.subheader("Gradio App")
55
+ components.html(
56
+ render_gradio_iframe(modified_url),
57
+ height=600,
58
+ scrolling=True
59
+ )
 
 
 
 
 
 
 
 
 
 
60
 
61
+ # JavaScript injection to set prompt (alternative approach, may be blocked by CORS)
62
+ st.markdown("""
63
+ <script>
64
+ function setPrompt(prompt) {
65
+ try {
66
+ const iframe = document.querySelector('iframe');
67
+ iframe.contentWindow.postMessage({
68
+ type: 'set_prompt',
69
+ prompt: prompt
70
+ }, '*');
71
+ } catch (e) {
72
+ console.error('Error sending prompt:', e);
73
+ }
74
+ }
75
+ </script>
76
+ """, unsafe_allow_html=True)
77
 
78
+ if prompt and apply_prompt:
79
+ # Attempt to send prompt via JavaScript (requires Gradio app to listen for postMessage)
80
+ st.markdown(f"""
81
+ <script>
82
+ setPrompt("{prompt}");
83
+ </script>
84
+ """, unsafe_allow_html=True)
85
 
86
+ # Notes and limitations
87
+ st.markdown("""
88
+ **Notes:**
89
+ - The Gradio app is embedded in an iframe, preserving its original interface.
90
+ - Prefilling prompts via URL parameters or JavaScript may not work if the Gradio app doesn't support these methods.
91
+ - If the app doesn't respond to the prompt, interact directly with the iframe below.
92
+ - To fully control the app, the Gradio app's API or source code would need to be inspected for supported endpoints.
93
+ """)