Advertisement
Guest User

Untitled

a guest
Jun 4th, 2025
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.54 KB | None | 0 0
  1. import openai
  2. import time
  3. from docx import Document
  4. from docx.shared import Inches
  5. import os
  6. from datetime import datetime
  7.  
  8. # Configuration
  9. OPENAI_API_KEY = "your-openai-api-key-here"  # Replace with your actual API key
  10. MODEL = "gpt-4"  # or "gpt-3.5-turbo" for cheaper option
  11. DELAY_BETWEEN_REQUESTS = 2  # seconds to avoid rate limiting
  12.  
  13. class StoryGenerator:
  14.     def __init__(self, api_key):
  15.         self.client = openai.OpenAI(api_key=api_key)
  16.         self.story_outline = ""
  17.         self.chapter_summaries = []
  18.         self.chapters = []
  19.        
  20.     def generate_story_outline(self, story_type="hero's journey", genre="fantasy", additional_notes=""):
  21.         """Generate initial story outline"""
  22.         prompt = f"""
  23.        Create a detailed story outline using the {story_type} storytelling arc in the {genre} genre.
  24.        
  25.        Include:
  26.        - Basic character development (protagonist, antagonist, supporting characters)
  27.        - World building elements
  28.        - Major plot points following the {story_type} structure
  29.        - Themes and character arcs
  30.        - Setting and atmosphere
  31.        
  32.        Additional requirements: {additional_notes}
  33.        
  34.        This should be a complete outline for a novella-length story that can be divided into 12 chapters.
  35.        """
  36.        
  37.         print("Generating story outline...")
  38.         response = self.client.chat.completions.create(
  39.             model=MODEL,
  40.             messages=[{"role": "user", "content": prompt}],
  41.             max_tokens=1500,
  42.             temperature=0.7
  43.         )
  44.        
  45.         self.story_outline = response.choices[0].message.content
  46.         print("✓ Story outline generated")
  47.         return self.story_outline
  48.    
  49.     def organize_into_chapters(self):
  50.         """Organize the story outline into 12 chapters"""
  51.         prompt = f"""
  52.        Based on this story outline:
  53.        
  54.        {self.story_outline}
  55.        
  56.        Organize this story into exactly 12 chapters. For each chapter, provide:
  57.        - Chapter number and title
  58.        - 2-3 sentence summary of what happens in that chapter
  59.        - Key characters involved
  60.        - Important plot points or developments
  61.        
  62.        Format each chapter summary clearly and number them 1-12.
  63.        """
  64.        
  65.         print("Organizing story into 12 chapters...")
  66.         time.sleep(DELAY_BETWEEN_REQUESTS)
  67.        
  68.         response = self.client.chat.completions.create(
  69.             model=MODEL,
  70.             messages=[{"role": "user", "content": prompt}],
  71.             max_tokens=1500,
  72.             temperature=0.7
  73.         )
  74.        
  75.         chapter_organization = response.choices[0].message.content
  76.         print("✓ Story organized into chapters")
  77.         return chapter_organization
  78.    
  79.     def extract_chapter_summaries(self, chapter_organization):
  80.         """Extract individual chapter summaries for later use"""
  81.         # This is a simple extraction - you might want to make this more robust
  82.         lines = chapter_organization.split('\n')
  83.         current_chapter = ""
  84.        
  85.         for line in lines:
  86.             if line.strip().startswith(('Chapter', 'CHAPTER')) and any(str(i) in line for i in range(1, 13)):
  87.                 if current_chapter:
  88.                     self.chapter_summaries.append(current_chapter.strip())
  89.                 current_chapter = line + '\n'
  90.             elif current_chapter and line.strip():
  91.                 current_chapter += line + '\n'
  92.        
  93.         if current_chapter:
  94.             self.chapter_summaries.append(current_chapter.strip())
  95.        
  96.         print(f"✓ Extracted {len(self.chapter_summaries)} chapter summaries")
  97.    
  98.     def write_chapter(self, chapter_number, chapter_summary):
  99.         """Write a single chapter based on its summary"""
  100.         prompt = f"""
  101.        Based on this story outline:
  102.        {self.story_outline}
  103.        
  104.        Write Chapter {chapter_number} with the following summary:
  105.        {chapter_summary}
  106.        
  107.        Write this as a complete chapter of approximately 800-1200 words. Include:
  108.        - Engaging prose and dialogue
  109.        - Character development
  110.        - Atmospheric descriptions
  111.        - Smooth narrative flow
  112.        - Proper chapter pacing
  113.        
  114.        Write in a engaging, literary style appropriate for the genre.
  115.        """
  116.        
  117.         print(f"Writing Chapter {chapter_number}...")
  118.         time.sleep(DELAY_BETWEEN_REQUESTS)
  119.        
  120.         response = self.client.chat.completions.create(
  121.             model=MODEL,
  122.             messages=[{"role": "user", "content": prompt}],
  123.             max_tokens=1500,
  124.             temperature=0.8
  125.         )
  126.        
  127.         chapter_content = response.choices[0].message.content
  128.         self.chapters.append({
  129.             'number': chapter_number,
  130.             'content': chapter_content,
  131.             'summary': chapter_summary
  132.         })
  133.        
  134.         print(f"✓ Chapter {chapter_number} completed ({len(chapter_content)} characters)")
  135.         return chapter_content
  136.    
  137.     def write_all_chapters(self):
  138.         """Write all 12 chapters"""
  139.         for i, summary in enumerate(self.chapter_summaries, 1):
  140.             try:
  141.                 self.write_chapter(i, summary)
  142.             except Exception as e:
  143.                 print(f"Error writing chapter {i}: {e}")
  144.                 continue
  145.    
  146.     def save_to_word_document(self, filename=None):
  147.         """Save the complete story to a Word document"""
  148.         if not filename:
  149.             timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  150.             filename = f"ai_generated_story_{timestamp}.docx"
  151.        
  152.         doc = Document()
  153.        
  154.         # Add title page
  155.         title_para = doc.add_heading('AI Generated Story', 0)
  156.         title_para.alignment = 1  # Center alignment
  157.        
  158.         doc.add_paragraph(f"Generated on: {datetime.now().strftime('%B %d, %Y')}")
  159.         doc.add_paragraph(f"Total Chapters: {len(self.chapters)}")
  160.         doc.add_page_break()
  161.        
  162.         # Add story outline
  163.         doc.add_heading('Story Outline', level=1)
  164.         doc.add_paragraph(self.story_outline)
  165.         doc.add_page_break()
  166.        
  167.         # Add each chapter
  168.         for chapter in self.chapters:
  169.             doc.add_heading(f"Chapter {chapter['number']}", level=1)
  170.             doc.add_paragraph(chapter['content'])
  171.             doc.add_page_break()
  172.        
  173.         doc.save(filename)
  174.         print(f"✓ Story saved to {filename}")
  175.         return filename
  176.  
  177. def main():
  178.     # Check if API key is set
  179.     if OPENAI_API_KEY == "your-openai-api-key-here":
  180.         print("❌ Please set your OpenAI API key in the OPENAI_API_KEY variable")
  181.         return
  182.    
  183.     # Initialize the story generator
  184.     generator = StoryGenerator(OPENAI_API_KEY)
  185.    
  186.     # Get user preferences
  187.     print("=== AI Story Generator ===\n")
  188.    
  189.     story_type = input("Enter story arc type (default: hero's journey): ").strip() or "hero's journey"
  190.     genre = input("Enter genre (default: fantasy): ").strip() or "fantasy"
  191.     additional_notes = input("Additional requirements (optional): ").strip()
  192.    
  193.     try:
  194.         # Step 1: Generate story outline
  195.         outline = generator.generate_story_outline(story_type, genre, additional_notes)
  196.         print("\n" + "="*50)
  197.         print("STORY OUTLINE:")
  198.         print("="*50)
  199.         print(outline)
  200.        
  201.         # Ask if user wants to continue or regenerate
  202.         while True:
  203.             choice = input("\nAre you satisfied with this outline? (y/n/regenerate): ").lower()
  204.             if choice in ['y', 'yes']:
  205.                 break
  206.             elif choice in ['regenerate', 'r']:
  207.                 outline = generator.generate_story_outline(story_type, genre, additional_notes)
  208.                 print("\n" + "="*50)
  209.                 print("REGENERATED STORY OUTLINE:")
  210.                 print("="*50)
  211.                 print(outline)
  212.             elif choice in ['n', 'no']:
  213.                 print("Exiting...")
  214.                 return
  215.        
  216.         # Step 2: Organize into chapters
  217.         chapter_org = generator.organize_into_chapters()
  218.         generator.extract_chapter_summaries(chapter_org)
  219.        
  220.         print("\n" + "="*50)
  221.         print("CHAPTER ORGANIZATION:")
  222.         print("="*50)
  223.         print(chapter_org)
  224.        
  225.         # Ask if user wants to proceed with writing
  226.         proceed = input(f"\nProceed to write all {len(generator.chapter_summaries)} chapters? This may take several minutes. (y/n): ")
  227.         if proceed.lower() not in ['y', 'yes']:
  228.             print("Stopping before chapter generation.")
  229.             return
  230.        
  231.         # Steps 3-14: Write all chapters
  232.         print("\n" + "="*50)
  233.         print("GENERATING CHAPTERS...")
  234.         print("="*50)
  235.        
  236.         generator.write_all_chapters()
  237.        
  238.         # Save to Word document
  239.         filename = generator.save_to_word_document()
  240.        
  241.         print("\n" + "="*50)
  242.         print("GENERATION COMPLETE!")
  243.         print("="*50)
  244.         print(f"Total chapters written: {len(generator.chapters)}")
  245.         print(f"Story saved to: {filename}")
  246.        
  247.         # Calculate approximate word count
  248.         total_chars = sum(len(chapter['content']) for chapter in generator.chapters)
  249.         approx_words = total_chars // 5  # Rough estimate
  250.         print(f"Approximate word count: {approx_words:,} words")
  251.        
  252.     except Exception as e:
  253.         print(f"❌ An error occurred: {e}")
  254.         print("Make sure your OpenAI API key is valid and you have sufficient credits.")
  255.  
  256. if __name__ == "__main__":
  257.     main()
  258.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement