Spaces:
Build error
Build error
File size: 21,700 Bytes
23f36d1 | 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 | import gradio as gr
import openai
import os
from dotenv import load_dotenv
import json
import logging
from fastapi import Request
# Load environment variables
load_dotenv()
# Set up OpenAI API key
openai.api_key = os.getenv("OPENAI_API_KEY")
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Define a dictionary of valid username/password pairs
USERS = {
"subhash": "dasyam100x"
}
# Story database
STORY_DATABASE = {
"Paytm: From Tea Stall to Digital Payments Giant": "In the bustling streets of Aligarh, a young Vijay Shekhar Sharma juggled his studies with long hours at his father's tea stall...",
"Zomato: The Foodie's Menu Card That Fed a Nation": "In 2008, two young IIT graduates, Deepinder Goyal and Pankaj Chaddah, found themselves spending more time waiting for restaurant menus than actually eating...",
"Byju's: The Tutor Who Taught a Country": "On the serene backwaters of Kerala, a young mathematics graduate named Byju Raveendran found himself tutoring a handful of students preparing for the CAT exam...",
"Ola: The Nightmare Cab Ride That Changed India's Transport": "In 2010, Bhavish Aggarwal, a young engineer from IIT Bombay, booked a cab for a weekend trip from Bangalore to Bandipur...",
"Oyo Rooms: The Teen Who Disrupted India's Hotel Industry": "In 2011, 18-year-old Ritesh Agarwal was crisscrossing India, staying at different budget hotels...",
"Nykaa: The Banker Who Beautified India": "In 2012, Falguni Nayar was at the peak of her career as the Managing Director of Kotak Mahindra Capital Company...",
"Zerodha: The Trader Who Democratized Stock Market": "In the early 2000s, Nithin Kamath was a teenage stock trader in Bangalore, juggling his studies with his passion for the markets...",
"Flipkart: The Booksellers Who Flipped Indian E-commerce": "In 2007, two computer science graduates, Sachin Bansal and Binny Bansal (no relation), were working at Amazon's development center in Bangalore...",
"Micromax: The Feature Phone That Outsmarted Giant": "In 2000, four friends - Rahul Sharma, Rajesh Agarwal, Sumeet Arora, and Vikas Jain - were running a software company in Delhi...",
"Café Coffee Day: The Coffee Beans That Woke Up India": "In the lush coffee plantations of Chikmagalur, Karnataka, a young V.G. Siddhartha was brewing a revolution...",
"Tata Motors: From Nano to Jaguar, A Giant's Leap": "In 2008, Tata Motors was at a crossroads. The company had just launched the Nano, touted as the world's cheapest car, but it was struggling with losses and a mountain of debt...",
"SpiceJet: The Phoenix of Indian Skies": "In December 2014, SpiceJet was on the brink of collapse. The airline had run out of cash, its flights were being cancelled en masse, and suppliers were refusing to extend credit...",
"Indian Railways: From Colonial Relic to Modern Marvel": "In the early 2000s, Indian Railways was a behemoth on the brink. The world's fourth-largest rail network was plagued by outdated infrastructure, frequent accidents, and massive financial losses...",
"Yes Bank: Banking on a Second Chance": "In March 2020, Yes Bank, once India's fifth-largest private sector bank, was on the verge of collapse...",
"Satyam Computers: Fraud to Redemption": "January 7, 2009, sent shockwaves through India's corporate world. Ramalinga Raju, founder and chairman of Satyam Computers, India's fourth-largest IT services firm, confessed to orchestrating a $1.5 billion accounting fraud...",
"Axis Bank: The Bank That Pivoted to Progress": "In the early 2000s, UTI Bank, as Axis Bank was then known, was struggling to find its footing in India's competitive banking landscape...",
"Arvind Mills: The Denim Dream That Refused to Fade": "In the late 1990s, Arvind Mills, once the world's third-largest denim maker, was on the brink of bankruptcy...",
"Thomas Cook India: Vacationing from Trouble": "September 2019 sent shockwaves through the global travel industry. Thomas Cook, the world's oldest travel company, collapsed, stranding thousands of travelers worldwide...",
"Sintex Industries: Moulding a New Future": "In the early 2000s, Sintex Industries was primarily known for one product: plastic water tanks...",
"Mahindra & Mahindra: From Steel to Wheels": "In the 1990s, Mahindra & Mahindra (M&M) was at a crossroads. Known primarily as a manufacturer of rugged, but outdated, utility vehicles and tractors, the company was struggling to compete in India's liberalized economy...",
}
LEADERSHIP_QUALITIES = [
"Generosity", "Integrity", "Loyalty", "Devotion", "Kindness", "Sincerity", "Self-control",
"Confidence", "Persuasiveness", "Ambition", "Resourcefulness", "Decisiveness", "Faithfulness",
"Patience", "Determination", "Persistence", "Fairness", "Cooperation", "Optimism", "Proactive",
"Charisma", "Ethics", "Relentlessness", "Authority", "Enthusiasm", "Boldness"
]
STORY_TYPES = [
"Where we came from: A founding Story",
"Why we can't stay here: A case-for-change story",
"Where we're going: A vision story",
"How we're going to get there: A strategy story",
"Why I lead the way I do: Leadership philosophy story",
"Why you should want to work here: A rallying story",
"Personal stories: Who you are, what you do, how you do it, and who you do it for",
"What we believe: A story about values",
"Who we serve: A customer story",
"What we do for our customers: A sales story",
"How we're different: A marketing story"
]
STORY_USE_CASES = [
"Personal Branding",
"Company Origin",
"Product Launch",
"Customer Success / Testimonials",
"Team Building"
]
STORY_TIME_FRAMES = [
"Childhood", "Teenage Years", "Early Career", "Mid-Career", "Recent Experiences", "Future Vision"
]
STORY_LENGTHS = [
"Short (250-500 words)",
"Medium (500-1000 words)",
"Long (1000-1500 words)"
]
NARRATIVE_STRUCTURES = {
"The Story Hanger": "A structure that hangs key elements of the story on a central theme or concept.",
"The Story Spine": "Once upon a time... Every day... Until one day... Because of that... Because of that... Until finally... And ever since then...",
"Hero's Journey": "A cyclical journey through Ordinary World, Call to Adventure, Trials, Transformation, and Return.",
"Beginning to End": "A straightforward chronological narrative from start to finish.",
"In Media Res": "Start the story in the middle of the action, then provide backstory as the narrative progresses.",
"Nested Loops": "Embed smaller stories within the main narrative to offer additional perspectives or background information.",
"The Cliffhanger": "End on a suspenseful note, leaving the audience curious and eager for more."
}
STORY_THEMES = [
"Overcoming the Monster",
"Rags to Riches",
"The Quest",
"Voyage and Return",
"Rebirth",
"Comedy",
"Tragedy"
]
def generate_story(story_origin, well_known_tale, story_use_case, story_time_frame, story_focus, story_type, guided_story, story_length,request: gr.Request):
message = f"""
Create a compelling story based on these parameters:
Story Origin: {story_origin}
"""
if well_known_tale:
message += f"Well-Known Tale: {well_known_tale}\n"
message += f"""
Story Use Case: {story_use_case}
Time Frame: {story_time_frame}
Focus (Qualities): {', '.join(story_focus)}
Type: {story_type}
Length: {story_length}
Guided Storytelling Framework:
{guided_story}
# Comprehensive Storytelling Prompt for Engaging Indian Leadership Narratives
Create a captivating and realistic story that demonstrates leadership qualities through a protagonist's journey. The story should be gripping, relatable, and incorporate logic and common sense throughout. Use storytelling techniques that engage emotions, where relationships, values, and conflicts bring the audience into the heart of the narrative.
## Key Requirements
1. Perspective: Write the story in third person perspective. Do not use "I", "we", or "you". Instead, use the characters' names or "he", "she", "they", etc.
2. Length: The story must be within the specified word range.
3. Realism: Ensure the story is grounded in reality, with plausible scenarios and solutions.
4. Engagement: The narrative should grip the reader from start to finish.
5. Detail: Provide rich, vivid details about characters, settings, and events.
6. Logic: Incorporate clear, logical thinking in problem-solving and decision-making.
7. Innovation: Present creative, yet realistic solutions to challenges.
8. Relatability: Make characters and situations relatable to the average reader.
9. Indian Context: Tailor the story for Indian audiences, incorporating "masala" (drama and excitement).
10. Accessibility: Use simple, gripping storytelling without complex English words.
## Story Elements
Incorporate these elements seamlessly into the narrative without explicitly labeling them:
1. Introduction: Set the scene and introduce the main character(s) in a compelling way.
2. Call to Action: Describe the event or situation that sets the story in motion, making it feel urgent and important.
3. Obstacles: Detail at least three main challenges faced by the protagonist, each with its own complexities.
4. Emotional Journey: Explore the range of emotions experienced by the protagonist, making them feel human and relatable.
5. Support: Introduce supporting characters or resources that aid the protagonist, showing the importance of teamwork and resourcefulness.
6. Resolution: Detail how the final goal was reached, focusing on the innovative and logical steps taken.
7. Reflection: Share the personal growth and lessons learned, tying them back to earlier events in the story.
## Storytelling Techniques
- Use a mix of narrative, dialogue, and internal thoughts to keep the story engaging, always maintaining the third-person perspective.
- Create tension and suspense throughout the story, not just at obvious conflict points.
- Use sensory details to make the settings and situations come alive.
- Develop a unique voice for each character through their dialogue and actions.
- Incorporate foreshadowing and callbacks to create a satisfying narrative arc.
## Problem-Solving and Innovation
- When presenting challenges, provide detailed context and explain why conventional solutions won't work.
- For each major problem, show the protagonist's thought process:
1. Analyze the situation
2. Consider multiple options
3. Evaluate pros and cons
4. Make a decision
5. Implement the solution
6. Adjust based on results
- Innovative solutions should be creative yet plausible. Explain the logic behind them and how they draw from the protagonist's experiences or knowledge.
- Show both successes and failures in problem-solving, demonstrating learning and growth.
- Provide detailed explanations of how problems were solved, including the specific logic and innovative approaches used.
- Give concrete examples of these solutions in action.
## Character Development
- Give the protagonist a rich backstory that influences their decisions and leadership style.
- Show how the protagonist's leadership skills evolve throughout the story.
- Develop supporting characters with their own motivations and growth arcs.
## Setting and Context
- Create a vivid, realistic setting that influences the story's events.
- Incorporate relevant details about the industry, organization, or community in which the story takes place.
- Use the setting to create additional challenges or opportunities for the protagonist.
## Themes to Incorporate
- The importance of ethical decision-making in leadership
- Balancing personal life with professional responsibilities
- The role of mentorship and continuous learning in leadership development
- Adapting to unexpected changes and crises
- Building and maintaining trust within a team or organization
## Final Notes
- Ensure the story flows naturally while incorporating all storytelling elements and the selected leadership qualities.
- The narrative should feel authentic to the Indian context, using relatable situations, cultural references, and local color.
- While incorporating "masala" for excitement, maintain the story's realism and focus on leadership lessons.
- Use simple language accessible to a wide audience, avoiding complex English words or phrases.
- Remember to maintain the third-person perspective throughout the entire story.
"""
if request:
print("Request headers dictionary:", request.headers)
print("IP address:", request.client.host)
print("Query parameters:", dict(request.query_params))
logger.info(f"Generate story message: {message}")
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a storytelling expert skilled in creating compelling narratives that highlight leadership qualities. Always write in third person perspective."},
{"role": "user", "content": message}
],
max_tokens=2000,
n=1,
stop=None,
temperature=0.7,
)
story = response.choices[0].message['content']
logger.info(f"Generated story response: {story}")
logger.info(f"===================================================================\n\n\n")
return story
def enhance_story(story, structure, theme):
message = f"""
Enhance the following story using the {structure} structure and the {theme} theme:
{NARRATIVE_STRUCTURES[structure]}
Original Story:
{story}
Please restructure the story to fit the chosen narrative structure and theme while maintaining its core elements and emotional impact.
"""
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a storytelling expert skilled in adapting narratives to different structures and themes."},
{"role": "user", "content": message}
],
max_tokens=2000,
n=1,
stop=None,
temperature=0.7,
)
return response.choices[0].message['content']
def polish_story(story, options):
message = f"""
Polish the following story by adding the selected elements: {', '.join(options)}
Original Story:
{story}
Please enhance the story with the selected elements, ensuring they integrate seamlessly and enhance the overall narrative.
"""
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a storytelling expert skilled in adding creative elements to enhance narratives."},
{"role": "user", "content": message}
],
max_tokens=2000,
n=1,
stop=None,
temperature=0.7,
)
return response.choices[0].message['content']
def create_interface():
def login(username, password):
if username in USERS and USERS[username] == password:
return gr.update(visible=False), gr.update(visible=True)
else:
return gr.update(visible=True), gr.update(visible=False)
with gr.Blocks() as demo:
gr.Markdown("# AI Storytelling Assistant")
with gr.Group() as login_group:
username = gr.Textbox(label="Username")
password = gr.Textbox(label="Password", type="password")
login_button = gr.Button("Login")
login_error = gr.Markdown(visible=False)
with gr.Group(visible=False) as main_interface:
with gr.Tab("Tier 1: Story Creation"):
story_origin = gr.Radio(
choices=["Personal Anecdote", "Adapt Well-Known Tale"],
label="Story Origin"
)
well_known_tale = gr.Dropdown(
choices=list(STORY_DATABASE.keys()),
label="Select a Well-Known Tale",
visible=False
)
story_use_case = gr.Dropdown(
choices=STORY_USE_CASES,
label="Story Use Case"
)
story_time_frame = gr.Dropdown(
choices=STORY_TIME_FRAMES,
label="Story Time Frame"
)
story_focus = gr.CheckboxGroup(
choices=LEADERSHIP_QUALITIES,
label="Story Focus (Leadership Qualities - Select 3-5)"
)
story_type = gr.Dropdown(
choices=STORY_TYPES,
label="Story Type"
)
story_length = gr.Dropdown(
choices=STORY_LENGTHS,
label="Story Length"
)
guided_story = gr.Textbox(
label="Guided Storytelling Framework",
placeholder="1. Describe the day it happened\n2. What was the Call to Action / Invitation\n3. Describe the obstacles (up to three) in 4 lines\n4. Explore emotions/fears experienced during the incident\n5. Recognize the helpers / any objects of help in the incident\n6. Detail the resolution / Reaching the final goal\n7. Reflect on personal growth or lessons learned",
lines=10,
value="1. It was a regular morning at work, but I felt a shift in the air...\n2. My manager called me to lead a high-profile project.\n3. I faced doubts from my peers, a tight deadline, and limited resources...\n4. I feared failure but felt the excitement of a new challenge.\n5. A mentor stepped in to guide me, and I had access to key tools.\n6. After overcoming all obstacles, the project succeeded...\n7. I learned the importance of perseverance and mentorship."
)
generate_button = gr.Button("Generate Story")
story_output = gr.Textbox(label="Generated Story", lines=20)
with gr.Tab("Tier 2: Story Enhancement"):
gr.Markdown("## Option 1: One-on-One Coaching")
storyteller_booking = gr.Dropdown(
choices=["Storyteller 1", "Storyteller 2", "Storyteller 3"], # Replace with actual storyteller names
label="Select a Storyteller for Coaching"
)
book_session_button = gr.Button("Book a Session")
gr.Markdown("## Option 2: AI-Powered Enhancement")
enhanced_story_input = gr.Textbox(label="Enter your story here", lines=10)
narrative_structure = gr.Dropdown(
choices=list(NARRATIVE_STRUCTURES.keys()),
label="Choose a narrative structure or technique"
)
narrative_structure_description = gr.Markdown()
story_theme = gr.Dropdown(
choices=STORY_THEMES,
label="Choose a story theme"
)
enhance_button = gr.Button("Enhance Story")
enhanced_story_output = gr.Textbox(label="Enhanced Story", lines=20)
with gr.Tab("Tier 3: Story Polishing"):
polishing_story_input = gr.Textbox(label="Enter your story here", lines=10)
polish_options = gr.CheckboxGroup(
choices=["Impactful quotes", "Poems", "Similes", "Metaphors", "Sensory descriptions", "Emotional resonance"],
label="Choose polishing options"
)
polish_button = gr.Button("Polish Story")
polished_story_output = gr.Textbox(label="Polished Story", lines=20)
book_final_session_button = gr.Button("Book a Session with a Professional Storyteller")
def update_narrative_structure_description(structure):
return NARRATIVE_STRUCTURES.get(structure, "")
def update_tale_visibility(choice):
return gr.update(visible=(choice == "Adapt Well-Known Tale"))
login_button.click(
login,
inputs=[username, password],
outputs=[login_group, main_interface]
)
story_origin.change(update_tale_visibility, inputs=[story_origin], outputs=[well_known_tale])
generate_button.click(
generate_story,
inputs=[story_origin, well_known_tale, story_use_case, story_time_frame, story_focus, story_type, guided_story, story_length],
outputs=story_output
)
narrative_structure.change(
update_narrative_structure_description,
inputs=[narrative_structure],
outputs=[narrative_structure_description]
)
enhance_button.click(
enhance_story,
inputs=[enhanced_story_input, narrative_structure, story_theme],
outputs=enhanced_story_output
)
polish_button.click(
polish_story,
inputs=[polishing_story_input, polish_options],
outputs=polished_story_output
)
return demo
# Launch the app
if __name__ == "__main__":
demo = create_interface()
demo.launch(server_name="0.0.0.0", share=True) |