To integrate CSS into your Python script, you can create a web-based interface that allows users to interact with your flip_text_api function. One of the most straightforward ways to achieve this is by using Gradio, a Python library that makes it easy to build customizable UI components around your machine learning models or functions.
Gradio allows you to add custom CSS to style your interface, enabling you to enhance the visual appeal and usability of your application.
Below, I'll guide you through the steps to create a Gradio interface for your flip_text_api function and incorporate custom CSS to style the interface.
1. Install Required Libraries
First, ensure you have the necessary libraries installed. You can install gradio and gradio_client using pip:
pip install gradio gradio_client
2. Create a Gradio Interface with Custom CSS
Here's how you can modify your script to include a Gradio interface with custom CSS:
import os
from gradio_client import Client
import gradio as gr
def flip_text_api(
prompt: str = "space warrior, beautiful, female, ultrarealistic, soft lighting, 8k",
negative_prompt: str = "3d, cartoon, anime, (deformed eyes, nose, ears, nose), bad anatomy, ugly",
model: str = "sd_xl_base_1.0.safetensors [be9edd61]",
steps: float = 20,
sampler: str = "DPM++ 2M Karras",
cfg_scale: float = 7,
resolution: str = "1024x1024",
seed: float = -1,
huggingface_token: str = None, # Optional: Only required for private Spaces
client_name: str = "prodia/sdxl-stable-diffusion-xl",
api_endpoint: str = "/flip_text"
) -> str:
"""
Interacts with the /flip_text API endpoint using gradio_client.
Parameters:
... [same as before]
Returns:
str: File path to the generated image.
"""
try:
if huggingface_token:
client = Client(client_name, token=huggingface_token)
else:
client = Client(client_name)
except Exception as e:
print(f"Error initializing Gradio Client: {e}")
return None
params = {
"prompt": prompt,
"negative_prompt": negative_prompt,
"model": model,
"steps": steps,
"sampler": sampler,
"cfg_scale": cfg_scale,
"resolution": resolution,
"seed": seed
}
try:
result = client.predict(
*params.values(),
api_name=api_endpoint
)
return result # This should be the filepath to the image
except Exception as e:
print(f"Error during API prediction: {e}")
return None
def main():
# Retrieve Hugging Face token from environment variable (if set)
hf_token = os.getenv('HUGGINGFACE_TOKEN') # Ensure you've set this if needed
# Define the Gradio interface
with gr.Blocks(css="""
/* Custom CSS */
body {
background-color: #f0f2f5;
}
.gradio-container {
max-width: 800px;
margin: auto;
padding: 20px;
border-radius: 10px;
background-color: #ffffff;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.gr-button {
background-color: #4CAF50;
color: white;
padding: 10px 24px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.gr-button:hover {
background-color: #45a049;
}
"""):
gr.Markdown("<h1 style='text-align: center; color: #333;'>Flip Text Image Generator</h1>")
with gr.Row():
with gr.Column():
prompt = gr.Textbox(
label="Prompt",
value="A serene landscape with mountains and a river at sunset.",
lines=2
)
negative_prompt = gr.Textbox(
label="Negative Prompt",
value="low resolution, blurry, distorted",
lines=2
)
model = gr.Textbox(
label="Model",
value="sd_xl_base_1.0.safetensors [be9edd61]"
)
steps = gr.Slider(
label="Steps",
minimum=1,
maximum=100,
value=25
)
sampler = gr.Dropdown(
label="Sampler",
choices=["Euler a", "DPM++ 2M Karras", "LMS", "DDIM"],
value="Euler a"
)
cfg_scale = gr.Slider(
label="CFG Scale",
minimum=1,
maximum=20,
value=8.5
)
resolution = gr.Textbox(
label="Resolution",
value="1024x1024"
)
seed = gr.Number(
label="Seed",
value=42
)
huggingface_token = gr.Textbox(
label="Hugging Face Token (optional)",
type="password"
)
submit = gr.Button("Generate Image")
with gr.Column():
output = gr.Image(
label="Generated Image"
)
status = gr.Textbox(
label="Status",
value="Awaiting input...",
interactive=False
)
def generate_image(prompt, negative_prompt, model, steps, sampler, cfg_scale, resolution, seed, huggingface_token):
status.update("Generating image...")
image_path = flip_text_api(
prompt=prompt,
negative_prompt=negative_prompt,
model=model,
steps=steps,
sampler=sampler,
cfg_scale=cfg_scale,
resolution=resolution,
seed=seed,
huggingface_token=huggingface_token
)
if image_path:
status.update("Image generated successfully!")
return image_path
else:
status.update("Failed to generate image.")
return None
submit.click(
fn=generate_image,
inputs=[prompt, negative_prompt, model, steps, sampler, cfg_scale, resolution, seed, huggingface_token],
outputs=output
)
# Launch the Gradio app
gr.launch()
if __name__ == "__main__":
main()
3. Explanation of the Modifications
-
Gradio Interface Setup:
gr.Blocks: This is a flexible layout system in Gradio that allows for more complex interfaces. Within gr.Blocks, you can arrange components in rows and columns.
- Custom CSS: The
css parameter in gr.Blocks allows you to inject custom CSS to style your interface. In the example, we've added styles to the background, container, and buttons.
-
Input Components:
- Textboxes: For inputs like
prompt, negative_prompt, model, etc.
- Sliders and Dropdowns: For inputs that have a range of possible values, like
steps and sampler.
- Password Field: The
huggingface_token is a sensitive input, so it's set as a password type to hide the input.
-
Output Components:
- Image Display: To show the generated image.
- Status Box: To provide feedback to the user about the generation process.
-
Generate Function:
- The
generate_image function calls your flip_text_api with the provided inputs and updates the status accordingly.
-
Launching the App:
gr.launch() starts the Gradio web server, allowing you to access the interface via a web browser.
4. Running the Script
Save the modified script to a Python file, for example, app.py. Ensure that your environment has the necessary dependencies installed and that the HUGGINGFACE_TOKEN environment variable is set if you're accessing a private Space.
Run the script using:
python app.py
After running, Gradio will provide a local URL (e.g., http://127.0.0.1:7860) where you can access the web interface. You'll see a styled interface where you can input the necessary parameters and generate images.
5. Customizing the CSS
The CSS provided in the gr.Blocks is basic and serves as an example. You can customize it further to match your desired aesthetics. Here are some ideas:
- Fonts: Change the font family or size to improve readability.
- Colors: Adjust background colors, button colors, and text colors to create a cohesive look.
- Layout: Modify the spacing, margins, and padding to make the interface more user-friendly.
- Animations: Add subtle animations for interactions like button clicks or image loading.
6. Advanced Styling with External CSS Files
If you prefer to manage your CSS separately, you can host an external CSS file and link it within the gr.Markdown component. Here's how:
-
Create a CSS File: For example, styles.css with your desired styles.
/* styles.css */
body {
background-color: #f0f2f5;
}
.custom-container {
max-width: 800px;
margin: auto;
padding: 20px;
border-radius: 10px;
background-color: #ffffff;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.gr-button {
background-color: #4CAF50;
color: white;
padding: 10px 24px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.gr-button:hover {
background-color: #45a049;
}
-
Host the CSS File: Place it in a directory accessible to your script or serve it via a local server.
-
Link the CSS in Gradio:
Modify the gr.Blocks to include the external CSS.
with gr.Blocks(css=open("styles.css").read()):
# Rest of the interface
7. Additional Enhancements
- Error Handling: Improve the error messages and handling to guide users in case something goes wrong.
- Loading Indicators: Add loading animations or progress bars to indicate that the image is being generated.
- Download Option: Provide a button for users to download the generated image directly from the interface.
- Responsive Design: Ensure that the interface looks good on different screen sizes, including mobile devices.
8. Security Considerations
- API Tokens: If you're using API tokens, ensure they're handled securely. Avoid hardcoding them and consider using environment variables or secure storage solutions.
- Input Validation: Validate user inputs to prevent misuse or unexpected behavior.
Conclusion
By integrating Gradio and custom CSS into your Python script, you can create a user-friendly and visually appealing web interface for your flip_text_api. This approach not only enhances the usability of your application but also makes it accessible to users who may not be comfortable running Python scripts directly.
Feel free to customize the interface and styles further to match your specific requirements and preferences.