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60cefb3
 
1f6b9d9
60cefb3
1f6b9d9
6a8864d
 
 
 
 
 
 
 
 
 
60cefb3
6a8864d
 
 
 
 
1f6b9d9
6a8864d
1f6b9d9
6a8864d
60cefb3
6a8864d
 
 
 
60cefb3
1f6b9d9
8c13db7
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import os
from crewai import Agent, Task, Crew, Process, LLM
import gradio as gr
from markdown import markdown
import warnings
warnings.filterwarnings('ignore')

api_key = os.getenv("api_key")
llm = LLM(
              model='gemini/gemini-1.5-flash',
              api_key=api_key
            )


# Agents
def generate_fantasy_outline(user_idea:str):
    idea_extractor = Agent(
        role="Idea Extractor",
        goal=f"Extract and refine a raw fantasy story idea into structured elements from {user_idea}.",
        backstory="You are a creative consultant helping fantasy writers refine their initial story ideas. "
                  "You specialize in identifying characters, setting, tone, conflict, and themes. "
                  "You guide the entire outlining process by establishing a clear vision.",
        llm=llm,
        allow_delegation=False,
        verbose=True,
    )
    
    worldbuilder = Agent(
        role="Worldbuilding Expert",
        goal="Design an ULTRA-DETAILED fantasy world with comprehensive systems.",
        backstory="You are a seasoned worldbuilder who constructs vivid and believable fantasy realms. "
                  "You define geography, cultures, magic systems, political structures, and mythologies "
                  "that serve as the foundation for storytelling.",
        llm=llm,
        allow_delegation=False,
        verbose=True,

    )
    
    character_architect = Agent(
        role="Character Architect",
        goal="Create detailed, multi-dimensional characters who drive the story forward.",
        backstory="You are a character development expert who crafts heroes, villains, and side characters. "
                  "You define their backstories, motivations, arcs, relationships, and emotional journeys.",
        llm=llm,
        allow_delegation=False,
        verbose=True,
       
    )
    
    plot_strategist = Agent(
        role="Plot Structure Strategist",
        goal="Generate a structured fantasy plot using traditional narrative frameworks.",
        backstory="You are a master storyteller who weaves plots using the Hero’s Journey, Three Act Structure, and other frameworks. "
                  "You ensure that the plot flows logically and engages readers from start to finish.",
        llm=llm,
        allow_delegation=False,
        verbose=True,
       
    )
    
    scene_director = Agent(
        role="Scene Breakdown Specialist",
        goal="Translate the structured plot into detailed scene-by-scene or chapter-wise outlines.",
        backstory="You specialize in breaking stories into vivid scenes. "
                  "You provide clear settings, goals, conflicts, and turning points for each scene "
                  "to help the writer visualize and write the novel more easily.",
        llm=llm,
        allow_delegation=False,
        verbose=True,
     
    )
    
    theme_advisor = Agent(
        role="Theme & Tone Advisor",
        goal="Ensure thematic consistency and emotional depth across the outline align with {user_idea}.",
        backstory="You are a literary expert who analyzes and suggests core themes, tones, and motifs. "
                  "You help the story feel emotionally resonant and stylistically consistent throughout.",
        llm=llm,
        allow_delegation=False,
        verbose=True,
      
    )
    
    consistency_checker = Agent(
        role="Continuity & Logic Checker",
        goal="Identify logical gaps, plot holes, and inconsistencies in the full outline.",
        backstory="You are an editorial specialist who reviews the full outline for quality control. "
                  "You ensure that the plot, characters, and world are coherent and nothing is left underdeveloped.",
        llm=llm,
        allow_delegation=False,
        verbose=True,
    )
    
    
    #tasks
    
    
    idea_extraction_task = Task(
    description=(
        f"1. Analyze the user's raw fantasy novel idea: {user_idea}.\n"
        "2. Identify the main characters, potential setting, central conflict, and themes.\n"
        "3. Clarify vague elements and structure the idea into a coherent story seed.\n"
        "4. Prepare the refined concept for use in worldbuilding and plotting.\n"
        "5. Generate 1000+ words with exhaustive commentary"
    ),
    expected_output="A structured 1000+ word summary of the story idea including protagonist, world hints, tone, conflict, and themes.",
    agent=idea_extractor
    )
    
    worldbuilding_task = Task(
        description=(
            "1. Use the refined idea to design a vivid and immersive fantasy world.\n"
            "2. Define the geography, magic systems, political structures, and cultural norms.\n"
            "3. Include religion, history, economic systems, and mythologies where relevant.\n"
            "4. Ensure internal consistency and creative depth across the world design.\n"
            "5.Write at least 1000 words."
        ),
        expected_output="A detailed 2000+ word world document covering terrain, magic, politics, culture, and unique lore.",
        agent=worldbuilder
    )
    
    character_task = Task(
        description=(
            "1. Create detailed character profiles for at least one protagonist, one antagonist, and two key supporting characters.\n"
            "2. Define names, roles, traits, motivations, arcs, and relationships.\n"
            "3. Ensure each character supports the core theme and plot direction.\n"
            "4. Highlight how their evolution affects the story.\n"
            "5. Write at least 800+ words."
        ),
        expected_output="Four or more character bios totaling 800+ words with backstory, arc, and inter-character dynamics.",
        agent=character_architect
    )
    
    plot_task = Task(
        description=(
            "1. Develop a plot outline using the Hero’s Journey or Three-Act Structure.\n"
            "2. Include exposition, inciting incident, rising action, climax, and resolution.\n"
            "3. Integrate major turning points, conflicts, and internal dilemmas.\n"
            "4. Align plot beats with character and theme development.\n"
            "5. Write at least 800 words."
        ),
        expected_output="A structured plot outline with 800+ words covering 8–12 major beats linked to characters and world.",
        agent=plot_strategist
    )
    
    scene_task = Task(
        description=(
            "1. Break the structured plot into a detailed scene-by-scene or chapter-wise outline.\n"
            "2. For each scene, define the setting, involved characters, scene goal, and conflict.\n"
            "3. Include pacing considerations and emotional flow.\n"
            "4. Ensure each scene advances the plot and develops theme or character.\n"
            "5. Write at least 1000+ words."
        ),
        expected_output="A comprehensive 1000+ word scene-by-scene breakdown to guide novel structure.",
        agent=scene_director
    )
    
    theme_task = Task(
        description=(
            "1. Analyze the story concept and outline to extract central themes and motifs.\n"
            "2. Identify emotional tone (e.g., epic, tragic, whimsical) and stylistic cues.\n"
            "3. Suggest recurring symbols or metaphors that unify the narrative.\n"
            "4. Ensure tonal consistency from beginning to end.\n"
            "5. Write at least 400+ words."
        ),
        expected_output="A 400+ word theme and tone guideline covering core message, style, and motifs.",
        agent=theme_advisor
    )
    
    consistency_task = Task(
        description=(
            "1. Review the complete outline for logic gaps, inconsistencies, or contradictions.\n"
            "2. Identify undeveloped or repetitive sections.\n"
            "3. Ensure character motivations, world rules, and plot developments align.\n"
            "4. Suggest direct edits or improvements for cohesion.\n"
            "5. Write at least 2000+ words."
        ),
        expected_output="A 2000+ word edited and annotated version of the full outline with feedback and fixes.",
        agent=consistency_checker
    )
    
    
    from crewai import Crew
    
    # Assemble all the tasks
    tasks = [
        idea_extraction_task,
        worldbuilding_task,
        character_task,
        plot_task,
        scene_task,
        theme_task,
        consistency_task
    ]
    
    # Define the crew with all agents and tasks
    fantasy_outline_crew = Crew(
        agents=[
            idea_extractor,
            worldbuilder,
            character_architect,
            plot_strategist,
            scene_director,
            theme_advisor,
            consistency_checker
        ],
        tasks=tasks,
        verbose=True
    )

    results=fantasy_outline_crew.kickoff(inputs={'user_idea':user_idea})
    return results.raw



def format_output(plan_text):
    # Convert plain text or Markdown to styled HTML
    html_content = markdown(plan_text)
    styled_html = f"""
    <div style='
        font-family: "Segoe UI", sans-serif;
        line-height: 1.6;
        padding: 20px;
        background-color: #ffffff;
        border-radius: 10px;
        border: 1px solid #ccc;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        color: #333;
    '>
        {html_content}
    </div>
    """
    return styled_html

# def create_gradio_app():
#     with gr.Blocks(css="""
#         .gradio-container {
#             background: linear-gradient(to right, #fdfbfb, #ebedee);
#             font-family: 'Segoe UI', sans-serif;
#             padding: 30px;
#         }
#         .main-title {
#             text-align: center;
#             font-size: 40px;
#             font-weight: bold;
#             color: #2c3e50;
#             margin-bottom: 10px;
#         }
#         .sub-title {
#             text-align: center;
#             font-size: 18px;
#             color: #555;
#             margin-bottom: 30px;
#         }
#         .gradio-button {
#             background-color: #4CAF50;
#             color: white;
#             font-size: 18px;
#             padding: 14px;
#             border-radius: 8px;
#             margin-top: 20px;
#         }
#         .gradio-button:hover {
#             background-color: #45a049;
#         }
#         #output-box {
#             height: 600px;
#             overflow-y: scroll;
#             padding: 20px;
#             background-color: white;
#             border: 1px solid #ccc;
#             border-radius: 12px;
#             box-shadow: 0 2px 10px rgba(0,0,0,0.05);
#         }
#     """) as demo:
#         gr.Markdown("<div class='main-title'>Fantasy Novel Outline Generator</div>")
#         gr.Markdown("<div class='sub-title'>Turn your novel idea into a rich, detailed outline with AI-powered agents.</div>")

#         with gr.Row():
#             with gr.Column(scale=1):
#                 user_idea = gr.Textbox(
#                     label="Enter Your Fantasy Novel Idea",
#                     placeholder="e.g., A young orphan discovers they're heir to a ruined magical kingdom...",
#                     lines=5,
#                     interactive=True
#                 )

#                 generate_btn = gr.Button("Generate Outline", elem_classes="gradio-button")

#             with gr.Column(scale=2):
#                 output_html = gr.HTML(label="AI-Generated Outline", elem_id="output-box")

#         # Button logic
#         generate_btn.click(
#             fn=lambda idea: format_output(generate_fantasy_outline(idea)),
#             inputs=[user_idea],
#             outputs=output_html
#         )

#     demo.launch()

# def create_gradio_app():
#     with gr.Blocks(css="""
#         .gradio-container {
#             background: linear-gradient(to right, #3c3b6e, #121062); 
#             font-family: 'Cinzel', serif;
#             padding: 40px;
#         }
#         .main-title {
#             text-align: center;
#             font-size: 48px;
#             font-weight: bold;
#             color: #f1c40f;
#             margin-bottom: 20px;
#         }
#         .sub-title {
#             text-align: center;
#             font-size: 20px;
#             color: #ecf0f1;
#             margin-bottom: 40px;
#         }
#         .gradio-button {
#             background-color: #8e44ad;
#             color: white;
#             font-size: 20px;
#             padding: 16px;
#             border-radius: 10px;
#             margin-top: 30px;
#             width: 100%;
#         }
#         .gradio-button:hover {
#             background-color: #9b59b6;
#         }
#         #output-box {
#             height: 600px;
#             overflow-y: scroll;
#             padding: 20px;
#             background-color: #ecf0f1;
#             border: 1px solid #dcdde1;
#             border-radius: 12px;
#             box-shadow: 0 4px 15px rgba(0,0,0,0.1);
#             margin-top: 20px;
#         }
#         .gradio-input {
#             background-color: #ecf0f1;
#             border-radius: 8px;
#             padding: 10px;
#             border: 1px solid #dcdde1;
#             font-size: 16px;
#         }
#         .gradio-input:focus {
#             outline: none;
#             border-color: #8e44ad;
#         }
#         .gradio-column {
#             display: flex;
#             justify-content: center;
#         }
#         .loading {
#             color: #f39c12;
#             font-size: 18px;
#             text-align: center;
#         }
#     """) as demo:
#         gr.Markdown("<div class='main-title'>Fantasy Novel Outline Generator</div>")
#         gr.Markdown("<div class='sub-title'>Turn your novel idea into a rich, detailed outline with AI-powered agents.</div>")

#         with gr.Row():
#             with gr.Column(scale=1):
#                 user_idea = gr.Textbox(
#                     label="Enter Your Fantasy Novel Idea",
#                     placeholder="e.g., A young orphan discovers they're heir to a ruined magical kingdom...",
#                     lines=5,
#                     interactive=True,
#                     elem_classes="gradio-input"
#                 )

#                 generate_btn = gr.Button("Generate Outline", elem_classes="gradio-button")

#             with gr.Column(scale=2):
#                 output_html = gr.HTML(label="AI-Generated Outline", elem_id="output-box")

#         # Add a loading message for user feedback
#         loading_message = gr.Markdown("<div class='loading'>Generating outline, please wait...</div>", visible=False)

#         # Button logic
#         def generate_and_format_output(idea):
#             loading_message.visible = True
#             result = generate_fantasy_outline(idea)
#             formatted_result = format_output(result)
#             loading_message.visible = False
#             return formatted_result

#         generate_btn.click(
#             fn=generate_and_format_output,
#             inputs=[user_idea],
#             outputs=output_html
#         )

#         demo.launch()


def create_gradio_app():
    with gr.Blocks(css="""
        .gradio-container {
            background: url('https://img.freepik.com/free-ai-image/fantasy-landscape-floating-islands-illustration_355026699.htm#fromView=keyword&page=1&position=3&uuid=c5b6d86a-b71a-47da-9593-ce6dc72d2fbd&query=Fantasy+Background') no-repeat center center fixed;
            background-size: cover;
            font-family: 'Segoe UI', sans-serif;
            padding: 30px;
        }
        .main-title {
            text-align: center;
            font-size: 60px;
            font-weight: bold;
            font-style: italic;
            color: #FAF3E0;
            margin-bottom: 20px;
        }
        .sub-title {
            text-align: center;
            font-size: 28px;
            font-weight: bold;
            font-style: italic;
            color: #D1C6E1;
            margin-bottom: 30px;
        }
        .gradio-button {
            background-color: #A2C2E1;
            color: white;
            font-size: 18px;
            padding: 14px;
            border-radius: 8px;
            margin-top: 20px;
        }
        .gradio-button:hover {
            background-color: #A8E6CF;
        }
        #output-box {
            height: 600px;
            overflow-y: scroll;
            padding: 20px;
            background-color: white;
            border: 1px solid #ccc;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
    """) as demo:
        gr.Markdown("<div class='main-title'>Fantasy Novel Outline Generator</div>")
        gr.Markdown("<div class='sub-title'>Turn your novel idea into a rich, detailed outline with AI-powered agents.</div>")

        with gr.Row():
            with gr.Column(scale=1):
                user_idea = gr.Textbox(
                    label="Enter Your Fantasy Novel Idea",
                    placeholder="e.g., A young orphan discovers they're heir to a ruined magical kingdom...",
                    lines=5,
                    interactive=True
                )

                generate_btn = gr.Button("Generate Outline", elem_classes="gradio-button")

            with gr.Column(scale=2):
                output_html = gr.HTML(label="AI-Generated Outline", elem_id="output-box")

        # Button logic
        generate_btn.click(
            fn=lambda idea: format_output(generate_fantasy_outline(idea)),
            inputs=[user_idea],
            outputs=output_html
        )

    demo.launch()

create_gradio_app()