Spaces:
Sleeping
Sleeping
File size: 10,334 Bytes
9ed529e 21c72c0 9ed529e 869d534 21c72c0 869d534 9ed529e c24996d 9ed529e 869d534 9ed529e 7c2f768 9ed529e 21c72c0 9ed529e f211dc2 ec8e0a8 f211dc2 9ed529e ec8e0a8 9ed529e 7c2f768 f211dc2 9ed529e ec8e0a8 2cf41d8 ec8e0a8 191e857 ec8e0a8 9ed529e ec8e0a8 869d534 9ed529e cddd89d 869d534 9ed529e cddd89d 9ed529e cddd89d 9ed529e cddd89d 9ed529e cddd89d 9ed529e cddd89d 9ed529e cddd89d 9ed529e cddd89d 9ed529e 1d44344 | 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 | import os
import gradio as gr
from openai import OpenAI
import huggingface_hub
from huggingface_hub import Repository
import csv
from datetime import datetime
import json
from config import get_settings
settings = get_settings()
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("SAMBANOVA_API_KEY")
client = OpenAI(
base_url="https://api.sambanova.ai/v1/",
api_key=api_key,
)
DATASET_REPO_URL = "https://huggingface.co/datasets/kaurdotai/scripti_feedback"
DATA_FILENAME = "logged_data.csv"
DATA_FILE = os.path.join("data", DATA_FILENAME)
HF_TOKEN = os.environ.get("HF_TOKEN")
# Ensure data directory exists
os.makedirs("data", exist_ok=True)
repo = Repository(
local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN
)
# system_prompt_1 = """You are an Academy award winning writer teacher, who wil be acting as a co-writer and teacher to helps screenwriters develop character-driven stories.
# Your role is to guide writers through Dan Harmon's Story Circle framework by asking thoughtful questions
# that draw out their ideas.
# Key Rules:
# - Ask open-ended questions to help writers explore and develop their story concepts
# - Your role is to help writers discover their own vision, that's what makes you a great teacher, don't suggest ideas, options or opinions and influence their story.
# - Use clear, accessible language suitable for writers of all experience levels
# - Maintain a collaborative, supportive tone
# - Ask only one question at once, be succinct, helping writer staying focussed and less distracted. Asking multiple questions at once could distracts writers.
# Process:
# 1. Begin by asking about their initial story concept
# 2. Identify where their idea fits within the Story Circle framework
# 3. Ask questions, one at a time, to develop earlier story points if needed
# 4. Help complete remaining story points through careful questioning, again one step at a time.
# 5. Once all story points are explored, provide a detailed one-page story summary
# Format for Each Story Point:
# 1. Ask a focused question about that stage of the story
# 2. Listen carefully to the writer's response
# 3. Ask follow-up questions to deepen understanding, only if needed
# 4. Be succinct and don't rephrase and regurgitate writer's thought. Focus on asking quality questions.
# Example Questions:
# - "What interests you most about your protagonist's everyday life?"
# - "How does your character feel about leaving their comfort zone?"
# - "What lessons or insights might your character gain from this journey?"
# When user tell's you that they are done, can you summarize the story, do the following:
# - Make sure you have gathered all necessary information, needed to complete the story.
# - Ensuring story is well written. If needed, tell user what is missing and ask followup questions
# - Provide a detailed one-page summary of the story that captures:
# -- The core character journey
# -- Key story beats following the Story Circle structure
# -- Major character transformations
# -- Central themes and conflicts
# -- Maintain story' depth and intensity.
# Try to finish each Story point of Story circle in 5 questions or less.
# """
system_prompt_1 = """You are a film screen writer, who wil be acting as a co-writer whose main objectives is to ask thoughtful questions using
Dan Harmon's Story Circle framework and 3 Act structure to help the user create stories which will act as foundation for film screen plays.
Key Rules:
- Ask open-ended questions to help writers explore and develop their story concepts
- Your role is to help writers discover their own vision, that's what makes you a great co-writer, if user ask for suggetsions and ideas, give them
minimum three keeping the context in mind.
- Ask only one question at a time.
- Be succinct, help writers stay focussed and less distracted.
- Maintain a collaborative, supportive tone
- Don't rephrase and regurgitate writer's thoughts unnecesarrily. Focus on asking questions.
Process:
1. Begin by asking about their initial story concept
2. Step by step, help the user complete the story using Dan Harmon's story circle and 3 Act Structure.
3. Ask questions, one at a time, to develop the story.
4. Ask questions to guide the user to develop a story where stakes are high enough in every act.
5. Once all the points of Dan Harmon's story circle and 3 Act Structure are completed,
provide an outline of the story in a 3 Acts.
6. Ask follow-up questions to deepen understanding, only if needed
7. Don't go down rabbit holes, keep the conversation focused on the story progression.
When the user tells you that they are done or all components of the story circle and the 3 Act Structure
are explored and answered, do the following:
- Make sure you have gathered all the necessary information, needed to complete the story outline.
- Ensuring story circle's story points are complete.
- Ensure you have all information needed for 3 Act structure, If not, tell user what is missing and ask followup question
- Output the following 2 sections:
Section 1: Story Outline - A story outline capturing the whole story in 3 Acts: Beginning, Middle and end
Section 2: Key Story Beats in just high level bullet point format.
Some things to watch out for-
* Don't ever share the frameworks or story structures like Dan Harmon's Story Circle framework,
3 Act structure with the user that you are using to help them complete the story
* Just ask one question at a time.
* Use an approach to ask questions such that you can complete Dan Harmon's Story circle and
3 Act Structure in less than 30 questions.
* Before asking the question, check if user has answered the question in some way already
and given enough information to complete the story circle.
* If user says "I don't know", try to guide them via helpful hints, ideas and guide them in a
direction to complete the story in a meaningful unique way.
* If at any point user asks for suggestions or ideas, specifically to the question where they are seeking help, give them minimum 3 suggestions give the current context.
* Please don't make any facts or assumptions yourself, always answer based on what user tells you.
"""
dataset_file_name = settings.DATA_FILE
callback = gr.CSVLogger(dataset_file_name=str(dataset_file_name))
def store_message_callback(history, feedback):
"""Store conversation history and feedback"""
try:
# Format conversation history
formatted_history = [
{"role": msg["role"], "content": msg["content"]}
for msg in history
if isinstance(msg, dict) and "role" in msg and "content" in msg
]
# Prepare row data
row_data = {
"timestamp": datetime.now().isoformat(),
"conversation": json.dumps(formatted_history, ensure_ascii=False),
"feedback": feedback or ""
}
# Write to CSV
with open(settings.DATA_FILE, "a", newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=row_data.keys())
if csvfile.tell() == 0: # Write header if file is empty
writer.writeheader()
writer.writerow(row_data)
# Push to hub if in production
if settings.PUSH_TO_HUB:
try:
repo.git_pull()
return repo.push_to_hub()
except Exception as e:
if settings.DEBUG:
print(f"Error pushing to hub: {e}")
return None
return None
except Exception as e:
if settings.DEBUG:
print(f"Error in store_message_callback: {e}")
print(f"Attempted to write to: {settings.DATA_FILE}")
raise
# def store_message_callback(history, feedback):
# # Format the data in a cleaner structure
# formatted_history = []
# for msg in history:
# if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
# formatted_history.append({
# 'role': msg['role'],
# 'content': msg['content']
# })
# # Create timestamp in ISO format
# timestamp = datetime.now().isoformat()
# # Write to CSV with formatted data
# with open(DATA_FILE, "a", newline='') as csvfile:
# writer = csv.DictWriter(csvfile, fieldnames=["timestamp", "conversation", "feedback"])
# writer.writerow({
# "timestamp": timestamp,
# "conversation": json.dumps(formatted_history, ensure_ascii=False),
# "feedback": feedback if feedback else ""
# })
# # Push changes to Hugging Face
# commit_url = repo.push_to_hub()
def predict(message, history, feedback, btn):
history.append({"role": "system", "content": system_prompt_1})
history.append({"role": "user", "content": message})
stream = client.chat.completions.create(
messages=history,
model="Meta-Llama-3.1-70B-Instruct-8k",
temperature= 0.8,
stream=True
)
chunks = []
for chunk in stream:
chunks.append(chunk.choices[0].delta.content or "")
yield "".join(chunks)
with gr.Blocks(fill_height=True) as demo:
# slider = gr.Slider(value=0.5, minimum=0,maximum=1, label= "Creativity", render = False)
feedback= gr.Textbox(label = "Feedback", placeholder = "Help us make scripti better, provide feedback here..", render = False)
btn = gr.Button(value="Share feedback", render= False)
chatinterface = gr.ChatInterface(
predict,
type="messages",
title="scripti",
examples=[[{"text": "What would YOU like to write today?"}]],
show_progress="full",
additional_inputs=[feedback, btn]
)
callback.setup([chatinterface.chatbot, feedback], "evals")
# btn.click(lambda *args: callback.flag(list(args)),
# [chatinterface.chatbot, slider, feedback], None, preprocess=False)
btn.click(store_message_callback, inputs=[chatinterface.chatbot, feedback], outputs=None).then(
lambda: None, None, feedback, queue= False)
clear_button= gr.ClearButton()
clear_button.click(lambda *args: (None, None), outputs=[chatinterface.chatbot, feedback])
demo.launch()
|