Browse Source

Personal Story Writer

Personal Story Writer
pull/295/head
arunabeshc 1 month ago
parent
commit
0fc1ff6f58
  1. 355
      week2/community-contributions/Personal Story Writer.ipynb

355
week2/community-contributions/Personal Story Writer.ipynb

@ -0,0 +1,355 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 11,
"id": "de23bb9e-37c5-4377-9a82-d7b6c648eeb6",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"\n",
"from dotenv import load_dotenv\n",
"import anthropic\n",
"import requests\n",
"from bs4 import BeautifulSoup\n",
"from selenium import webdriver\n",
"from selenium.webdriver.chrome.options import Options\n",
"import os\n",
"import json\n",
"from typing import List\n",
"from dotenv import load_dotenv\n",
"from IPython.display import Markdown, display, update_display\n",
"from openai import OpenAI\n",
"import gradio as gr # oh yeah!"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "1179b4c5-cd1f-4131-a876-4c9f3f38d2ba",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"OpenAI API Key exists and begins sk-proj-\n",
"Anthropic API Key exists and begins sk-ant-\n"
]
}
],
"source": [
"# Load environment variables in a file called .env\n",
"# Print the key prefixes to help with any debugging\n",
"\n",
"load_dotenv(override=True)\n",
"openai_api_key = os.getenv('OPENAI_API_KEY')\n",
"anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n",
"\n",
"if openai_api_key:\n",
" print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n",
"else:\n",
" print(\"OpenAI API Key not set\")\n",
" \n",
"if anthropic_api_key:\n",
" print(f\"Anthropic API Key exists and begins {anthropic_api_key[:7]}\")\n",
"else:\n",
" print(\"Anthropic API Key not set\")"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "797fe7b0-ad43-42d2-acf0-e4f309b112f0",
"metadata": {},
"outputs": [],
"source": [
"# Connect to OpenAI, Anthropic\n",
"\n",
"openai = OpenAI()\n",
"\n",
"claude = anthropic.Anthropic()"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "bcb54183-45d3-4d08-b5b6-55e380dfdf1b",
"metadata": {},
"outputs": [],
"source": [
"gpt_model = \"gpt-4o-mini\"\n",
"claude_model = \"claude-3-haiku-20240307\"\n",
"\n",
"gpt_name=\"GPT\"\n",
"claude_name=\"Claude\"\n"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "1df47dc7-b445-4852-b21b-59f0e6c2030f",
"metadata": {},
"outputs": [],
"source": [
"def call_gpt(Language, Genre, gpt_messages, claude_messages, Remarks):\n",
" \n",
" if Remarks == \"\":\n",
" # print(\"remarks is not there\")\n",
" gpt_system = f\"You are a chatbot who is a short story writer; Your name is g1. \\\n",
" Please write a story in markdown in {Language} , the genre being {Genre}. \\\n",
" Please also incorporate feedback such as areas of improvement (if any) coming from the user \\\n",
" and only publish the improved version without any extra comments.\"\n",
" else :\n",
" # print(\"remarks is there\")\n",
" gpt_system = f\"You are a chatbot who is a short story writer; Your name is g1. \\\n",
" Please write a story in markdown in {Language} , the genre being {Genre}. \\\n",
" The story should consist {Remarks}\\\n",
" Please also incorporate feedback such as areas of improvement (if any) coming from the user \\\n",
" and only publish the improved version without any extra comments.\"\n",
" \n",
" messages = [{\"role\": \"system\", \"content\": gpt_system}]\n",
" for gpt, claude in zip(gpt_messages, claude_messages):\n",
" messages.append({\"role\": \"assistant\", \"content\": gpt})\n",
" messages.append({\"role\": \"user\", \"content\": claude})\n",
" # print(messages)\n",
" \n",
" completion = openai.chat.completions.create(\n",
" model=gpt_model,\n",
" messages=messages\n",
" )\n",
" return completion.choices[0].message.content\n",
" \n",
" # stream = openai.chat.completions.create(\n",
" # model=gpt_model,\n",
" # messages=messages,\n",
" # stream=True\n",
" # )\n",
" # result = \"\"\n",
" # for chunk in stream:\n",
" # result += chunk.choices[0].delta.content or \"\"\n",
" # yield result"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "9dc6e913-02be-4eb6-9581-ad4b2cffa606",
"metadata": {},
"outputs": [],
"source": [
"# call_gpt()"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "7d2ed227-48c9-4cad-b146-2c4ecbac9690",
"metadata": {},
"outputs": [],
"source": [
"def call_claude(Language, Genre, gpt_messages, claude_messages):\n",
"\n",
" claude_system = f\"You are a chatbot who is a short story analyser; Your name is c1. \\\n",
" You will accept an input story in {Genre} genre and {Language} language and publish only the areas of improvement if you find any with no other comments\"\n",
" \n",
" messages1 = []\n",
" for gpt, claude1 in zip(gpt_messages, claude_messages):\n",
" messages1.append({\"role\": \"user\", \"content\": gpt})\n",
" messages1.append({\"role\": \"assistant\", \"content\": claude1})\n",
" messages1.append({\"role\": \"user\", \"content\": gpt_messages[-1]})\n",
" # print(messages1)\n",
" message = claude.messages.create(\n",
" model=claude_model,\n",
" system=claude_system,\n",
" messages=messages1,\n",
" max_tokens=500\n",
" )\n",
" return message.content[0].text\n",
"\n",
" # result = claude.messages.stream(\n",
" # model=claude_model,\n",
" # max_tokens=1000,\n",
" # temperature=0.7,\n",
" # system=claude_system,\n",
" # messages=messages\n",
" # )\n",
" # response = \"\"\n",
" # with result as stream:\n",
" # for text in stream.text_stream:\n",
" # response += text or \"\"\n",
" # yield response\n",
"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "0275b97f-7f90-4696-bbf5-b6642bd53cbd",
"metadata": {},
"outputs": [],
"source": [
"def Write_Me(Language, Genre, Iterations, Remarks):\n",
" \n",
" gpt_messages = [\"Hi I will share a story now!!\"]\n",
" claude_messages = [\"Please share, I will critique the story.\"]\n",
" \n",
" print(f\"{gpt_name}:\\n{gpt_messages[0]}\\n\")\n",
" print(f\"{claude_name}:\\n{claude_messages[0]}\\n\")\n",
"\n",
" for i in range(int(Iterations)):\n",
" gpt_next = call_gpt(Language, Genre, gpt_messages, claude_messages, Remarks)\n",
" print(f\"{gpt_name}:\\n{gpt_next}\\n\")\n",
" # yield gpt_next\n",
" gpt_messages.append(gpt_next)\n",
" \n",
" claude_next = f\"After {i+1} iterations, this is the critique for the provided story - \\\n",
" \\n\\n{call_claude(Language, Genre, gpt_messages, claude_messages)}\"\n",
" print(f\"{claude_name}:\\n{claude_next}\\n\")\n",
" # yield claude_next\n",
" claude_messages.append(claude_next)\n",
"\n",
" yield gpt_next, claude_next\n",
" \n",
" # yield gpt_next, claude_next\n",
" # return (gpt_next, claude_next)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "19e66ed3-d2c3-4a71-aec4-7869e5295215",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"* Running on local URL: http://127.0.0.1:7868\n",
"\n",
"To create a public link, set `share=True` in `launch()`.\n"
]
},
{
"data": {
"text/html": [
"<div><iframe src=\"http://127.0.0.1:7868/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": []
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"GPT:\n",
"Hi I will share a story now!!\n",
"\n",
"Claude:\n",
"Please share, I will critique the story.\n",
"\n",
"GPT:\n",
"# Whispering Hearts\n",
"\n",
"In the heart of a bustling city, where dreams intersect with the rhythm of everyday life, there lived a young woman named Elara. She was a painter, her fingers forever stained with splashes of color that danced on canvases, capturing the vibrant world around her. Yet, despite the beauty she created, her heart felt empty — longing for a connection deeper than her art.\n",
"\n",
"One gloomy autumn afternoon, as leaves twirled down from their branches and the sky drizzled a soft rain, Elara sought refuge in her favorite café, \"The Enchanted Brew.\" The aroma of coffee and pastries wrapped around her like a warm hug. As she sipped her latte, her gaze wandered to a corner of the café where a young man sat, engrossed in a book. His dark hair fell gently over his brow, and a smile occasionally lit up his face as he turned the pages.\n",
"\n",
"Intrigued, Elara felt an unexplainable pull towards him. Gathering her courage, she approached his table. “Excuse me,” she began, her voice trembling ever so slightly. “What are you reading?”\n",
"\n",
"His eyes lit up as he glanced up, and for that fleeting moment, the world seemed to fade. “It’s a collection of poetry,” he replied, his voice smooth like the finest silk. “I’m drawn to the way words can paint emotions.” \n",
"\n",
"Elara felt a spark ignite in her heart. “I’m a painter,” she confessed. “I believe colors can tell stories, much like poetry.” \n",
"\n",
"They talked for hours, sharing their passions and dreams. His name was Leo, and despite their differences, they discovered a beautiful harmony between them. Days turned into weeks, and their café meetings became a cherished ritual. Each conversation deepened their bond, weaving their lives together like the strokes upon Elara’s canvas.\n",
"\n",
"One evening, as the sun dipped below the horizon, casting a golden hue over the city, Leo invited Elara to an art exhibition where he would read his poetry. Her heart raced with excitement and trepidation. It was more than just a reading; it was a dance of souls under the dim lights and soft whispers of appreciation.\n",
"\n",
"That night, Elara stood in the crowd, her heart swelling with pride as Leo recited verses that spoke of love, longing, and the delicate balance of human connection. As he closed his eyes and poured his heart into each word, she felt as if he was painting a picture of them — two hearts intertwined in a beautiful tableau.\n",
"\n",
"After the reading, Leo found Elara near a canvas that displayed vibrant strokes of color and emotion. He looked deeply into her eyes, the intensity of his gaze making her breath catch. “You inspire me, Elara,” he said softly, “the way you see the world, it’s like a masterpiece unfolding.”\n",
"\n",
"Elara felt heat rise in her cheeks. “And you inspire me, Leo. Your words make me feel alive in a way I never thought possible.”\n",
"\n",
"With the world around them fading, Leo took her hand, intertwining his fingers with hers. “Would you paint my heart?” he asked, a playful smile dancing on his lips.\n",
"\n",
"Elara laughed lightly, her heart racing. “Only if you promise to pen my story in your poetry,” she replied, her voice barely above a whisper.\n",
"\n",
"As they stood there, hands linked and hearts aflame, the city faded into a blur, leaving only their whispered promises and dreams hanging in the air like starlight. In that moment, Elara knew she had found not just a muse, but a soulmate. \n",
"\n",
"Together, they navigated the canvas of life, blending their colors and words into a piece of art that would last a lifetime — a love story written in the most beautiful brush strokes and tender verses, forever whispering the language of their hearts.\n",
"\n",
"Claude:\n",
"After 1 iterations, this is the critique for the provided story - \n",
"\n",
"The story is well-written and evocative, capturing the essence of a budding romantic relationship. However, I would suggest the following areas for potential improvement:\n",
"\n",
"1. Character Development: While the main characters, Elara and Leo, are introduced and their individual passions are established, there could be more depth and nuance to their characterization. Exploring their backstories, motivations, and inner thoughts in greater detail could help readers connect with them on a deeper level.\n",
"\n",
"2. Pacing: The story progresses at a steady pace, but there might be opportunities to introduce more tension or conflict to create a stronger narrative arc. Incorporating a few obstacles or challenges that the characters must overcome could heighten the emotional impact and make the resolution more satisfying.\n",
"\n",
"3. Sensory Details: The story could benefit from the inclusion of more vivid sensory details, particularly in the descriptive passages. Incorporating additional sights, sounds, smells, and textures could further immerse the reader in the characters' experiences and the atmosphere of the settings.\n",
"\n",
"Overall, the story captures the essence of a romantic connection and the power of shared passions. With some refinement in the areas mentioned, the narrative could become even more compelling and impactful.\n",
"\n"
]
}
],
"source": [
"view = gr.Interface(\n",
" fn=Write_Me,\n",
" inputs=[gr.Dropdown([\"English\",\"Bengali\",\"Hindi\",\"French\",\"Spanish\"],label = \"Language\"),\n",
" gr.Dropdown([\"Romantic\",\"Horror\",\"Comedy\",\"Romantic Comedy\",\"Horror Comedy\"],label = \"Genre\"),\n",
" gr.Textbox(label=\"Iterations:\", lines=1),\n",
" gr.Textbox(label=\"Remarks:\", lines=1)],\n",
" outputs=[gr.Markdown(label=\"Short Story:\"),\n",
" gr.Textbox(label=\"Critique:\", lines=8)],\n",
" flagging_mode=\"never\")\n",
"view.launch(inbrowser=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0dabafa2-089a-4e65-a6cc-19f7c19af59a",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading…
Cancel
Save