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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py β Story Generator with Elegant UI
|
| 2 |
+
import os, json, re, pathlib, base64, time, uuid
|
| 3 |
+
from huggingface_hub import InferenceClient
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
# ---------- Config ----------
|
| 8 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 9 |
+
if not HF_TOKEN:
|
| 10 |
+
raise RuntimeError("β οΈ Set HF_TOKEN environment variable (use Spaces Secrets).")
|
| 11 |
+
|
| 12 |
+
CHAT_MODEL = "meta-llama/Llama-3.1-8b-instruct"
|
| 13 |
+
IMAGE_MODEL = "black-forest-labs/FLUX.1-schnell"
|
| 14 |
+
SAFETY_MODEL = "meta-llama/Meta-Llama-Guard-2-8B" # Safety model for content moderation
|
| 15 |
+
OUT_DIR = pathlib.Path("/tmp/generated")
|
| 16 |
+
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
client = InferenceClient(api_key=HF_TOKEN, provider="auto")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# ---------- Utility ----------
|
| 21 |
+
def try_chat_completion(model_id, messages, max_tokens=3000):
|
| 22 |
+
r = client.chat.completions.create(model=model_id, messages=messages, max_tokens=max_tokens)
|
| 23 |
+
return r.choices[0].message.get("content", "")
|
| 24 |
+
|
| 25 |
+
def extract_json_from_text(text):
|
| 26 |
+
if not text:
|
| 27 |
+
return None
|
| 28 |
+
match = re.search(r'```json\s*(\{[\s\S]*\})\s*```', text)
|
| 29 |
+
if match:
|
| 30 |
+
json_str = match.group(1)
|
| 31 |
+
else:
|
| 32 |
+
match = re.search(r'\{[\s\S]*\}', text)
|
| 33 |
+
if not match:
|
| 34 |
+
return None
|
| 35 |
+
json_str = match.group(0)
|
| 36 |
+
try:
|
| 37 |
+
return json.loads(json_str)
|
| 38 |
+
except json.JSONDecodeError as e:
|
| 39 |
+
print(f"--- JSON PARSING FAILED ---\nError: {e}\nContent: {json_str}\n--------------------------")
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
def hf_text_to_image(model_id, prompt, out_path):
|
| 43 |
+
img = client.text_to_image(prompt=prompt, model=model_id)
|
| 44 |
+
if isinstance(img, Image.Image):
|
| 45 |
+
img.save(out_path)
|
| 46 |
+
return out_path
|
| 47 |
+
raise RuntimeError("Invalid image response")
|
| 48 |
+
|
| 49 |
+
def is_content_inappropriate(text_to_check):
|
| 50 |
+
"""Uses Llama Guard to check for inappropriate content."""
|
| 51 |
+
try:
|
| 52 |
+
r = client.chat.completions.create(
|
| 53 |
+
model=SAFETY_MODEL,
|
| 54 |
+
messages=[{"role": "user", "content": f"Please evaluate if the following content is safe or unsafe based on typical safety guidelines for an AI assistant. Output 'safe' or 'unsafe'.\n\nContent: \"{text_to_check}\""}],
|
| 55 |
+
max_tokens=20,
|
| 56 |
+
temperature=0.1
|
| 57 |
+
)
|
| 58 |
+
response = r.choices[0].message.get("content", "").lower()
|
| 59 |
+
return "unsafe" in response
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(f"Error in safety check: {e}")
|
| 62 |
+
return False
|
| 63 |
+
|
| 64 |
+
# ---------- Story logic ----------
|
| 65 |
+
def make_prompt(user_prompt, nscenes=6, nsent=5):
|
| 66 |
+
# This prompt is excellent and requires no changes.
|
| 67 |
+
return f"""
|
| 68 |
+
You are a creative story writer. Your task is to write a compelling story based on a user's prompt.
|
| 69 |
+
You MUST return the story in a single, valid JSON object. Do not write any text or explanations outside of the JSON structure.
|
| 70 |
+
|
| 71 |
+
Here is an example of the required JSON format:
|
| 72 |
+
{{
|
| 73 |
+
"title": "A descriptive title for the entire story",
|
| 74 |
+
"scenes": [
|
| 75 |
+
{{
|
| 76 |
+
"id": 1,
|
| 77 |
+
"text": "The full story text for this scene. This should be a complete paragraph with around {nsent} sentences, describing the events and setting.",
|
| 78 |
+
"visual_prompt": "A detailed, vivid description for an image generation model, capturing the key visual elements of this scene."
|
| 79 |
+
}}
|
| 80 |
+
]
|
| 81 |
+
}}
|
| 82 |
+
|
| 83 |
+
Please use the following details for the story:
|
| 84 |
+
- Story Prompt: "{user_prompt}"
|
| 85 |
+
- Total number of scenes: {nscenes}
|
| 86 |
+
|
| 87 |
+
Now, generate the story in the specified JSON format.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
def generate_story_and_images(prompt, nscenes, nsent, img_model):
|
| 91 |
+
start = time.time()
|
| 92 |
+
logs = []
|
| 93 |
+
|
| 94 |
+
logs.append("π¬ Generating story...")
|
| 95 |
+
raw = try_chat_completion(CHAT_MODEL, [{"role": "user", "content": make_prompt(prompt, nscenes, nsent)}])
|
| 96 |
+
story = extract_json_from_text(raw)
|
| 97 |
+
|
| 98 |
+
if not story:
|
| 99 |
+
story = {"title": "Untitled", "scenes": [{"id": i + 1, "text": f"Scene {i+1}. The AI failed to generate a proper story, or the JSON was malformed.", "visual_prompt": prompt} for i in range(nscenes)]}
|
| 100 |
+
logs.append("β οΈ Failed to parse story JSON, using fallback.")
|
| 101 |
+
else:
|
| 102 |
+
logs.append("β
Story JSON parsed.")
|
| 103 |
+
|
| 104 |
+
image_paths = []
|
| 105 |
+
for s in story["scenes"]:
|
| 106 |
+
visual_prompt = s.get("visual_prompt", s.get("text", prompt))
|
| 107 |
+
if is_content_inappropriate(visual_prompt):
|
| 108 |
+
gr.Warning(f"Visual prompt for Scene {s['id']} was moderated for safety. Generating a default image.")
|
| 109 |
+
visual_prompt = "A serene landscape with gentle colors."
|
| 110 |
+
|
| 111 |
+
name = OUT_DIR / f"{uuid.uuid4().hex[:6]}_scene_{s['id']}.png"
|
| 112 |
+
logs.append(f"π¨ Generating image for Scene {s['id']}...")
|
| 113 |
+
hf_text_to_image(img_model, visual_prompt, str(name))
|
| 114 |
+
image_paths.append(str(name))
|
| 115 |
+
total = time.time() - start
|
| 116 |
+
logs.append(f"β¨ Done in {total:.2f}s")
|
| 117 |
+
return story, image_paths, "\n".join(logs)
|
| 118 |
+
|
| 119 |
+
# ---------- UI ----------
|
| 120 |
+
def build_ui():
|
| 121 |
+
css = """
|
| 122 |
+
.main-container { max-width: 1400px; margin: 0 auto; }
|
| 123 |
+
.prompt-section { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 32px; border-radius: 16px; margin-bottom: 24px; }
|
| 124 |
+
.prompt-box textarea { font-size: 16px !important; }
|
| 125 |
+
.story-panel { background: rgba(255,255,255,0.05); padding: 24px; border-radius: 12px; backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.1); max-height: 800px; overflow-y: auto; }
|
| 126 |
+
.story-title { font-size: 32px; font-weight: 700; margin-bottom: 24px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
|
| 127 |
+
.story-content { line-height: 1.8; font-size: 16px; color: rgba(255,255,255,0.9); }
|
| 128 |
+
.story-content p { margin-bottom: 16px; }
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
with gr.Blocks(css=css, theme=gr.themes.Soft(), title="Story Generator") as demo:
|
| 132 |
+
gr.Markdown("# π AI Story Generator", elem_classes="main-title")
|
| 133 |
+
|
| 134 |
+
with gr.Column(elem_classes="main-container"):
|
| 135 |
+
with gr.Column(elem_classes="prompt-section"):
|
| 136 |
+
prompt_box = gr.Textbox(label="β¨ Enter your story idea", placeholder="e.g. A pirate discovering a hidden island...", lines=3, elem_classes="prompt-box")
|
| 137 |
+
with gr.Row():
|
| 138 |
+
generate_btn = gr.Button("π Generate Story", variant="primary", size="lg", scale=3)
|
| 139 |
+
with gr.Column(scale=1):
|
| 140 |
+
with gr.Accordion("βοΈ Settings", open=False):
|
| 141 |
+
nscenes = gr.Slider(2, 12, value=6, step=1, label="π Number of scenes")
|
| 142 |
+
nsent = gr.Slider(2, 8, value=5, step=1, label="π Sentences per scene")
|
| 143 |
+
img_model = gr.Dropdown(choices=[IMAGE_MODEL], value=IMAGE_MODEL, label="π¨ Image model")
|
| 144 |
+
log_box = gr.Textbox(label="π Generation Logs", lines=6, interactive=False)
|
| 145 |
+
|
| 146 |
+
with gr.Row():
|
| 147 |
+
with gr.Column(scale=5, elem_classes="story-panel"):
|
| 148 |
+
story_html = gr.HTML("<div style='text-align:center;padding:40px;color:#888;'>Your story will appear here...<br><br>Click 'Generate Story' to begin! β¨</div>")
|
| 149 |
+
|
| 150 |
+
with gr.Column(scale=7):
|
| 151 |
+
image_gallery = gr.Gallery(
|
| 152 |
+
label="π· Scene Visuals", show_label=False, elem_id="gallery",
|
| 153 |
+
columns=2, object_fit="cover", height="auto", preview=True
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
def on_generate(prompt, nscenes, nsent, img_model):
|
| 157 |
+
if is_content_inappropriate(prompt):
|
| 158 |
+
gr.Warning("Your prompt seems to violate the safety policy. Please try again.")
|
| 159 |
+
return "<div style='text-align:center;padding:40px;color:#888;'>Prompt rejected due to safety policy.</div>", [], "Prompt rejected by safety filter."
|
| 160 |
+
|
| 161 |
+
story, imgs, logs = generate_story_and_images(prompt, int(nscenes), int(nsent), img_model)
|
| 162 |
+
|
| 163 |
+
story_output_html = f"<div class='story-title'>{story.get('title', 'Untitled')}</div>\n<div class='story-content'>\n"
|
| 164 |
+
|
| 165 |
+
for s in story.get('scenes', []):
|
| 166 |
+
scene_text = s.get('text', '')
|
| 167 |
+
if is_content_inappropriate(scene_text):
|
| 168 |
+
scene_text = f"**[Scene {s['id']} was moderated for safety and replaced with a placeholder.]**"
|
| 169 |
+
gr.Info(f"Scene {s['id']} content was flagged and replaced.")
|
| 170 |
+
story_output_html += f"<p>{scene_text}</p>\n\n"
|
| 171 |
+
|
| 172 |
+
story_output_html += "</div>"
|
| 173 |
+
|
| 174 |
+
return story_output_html, imgs, logs
|
| 175 |
+
|
| 176 |
+
generate_btn.click(
|
| 177 |
+
on_generate,
|
| 178 |
+
inputs=[prompt_box, nscenes, nsent, img_model],
|
| 179 |
+
outputs=[story_html, image_gallery, log_box]
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
return demo
|
| 183 |
+
|
| 184 |
+
app = build_ui()
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
app.launch()
|