Spaces:
Sleeping

File size: 13,974 Bytes
9ed529e
21c72c0
9ed529e
 
 
 
 
869d534
 
21c72c0
869d534
9ed529e
 
 
 
 
 
 
 
 
c24996d
9ed529e
 
 
 
 
869d534
 
 
9ed529e
7c2f768
9ed529e
21c72c0
 
9ed529e
f211dc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7df61
6334b6a
 
f211dc2
9ed529e
 
6334b6a
 
 
 
9ed529e
7c2f768
f211dc2
9ed529e
6334b6a
 
 
 
 
 
2cf41d8
 
6334b6a
 
 
 
 
 
 
 
 
 
 
 
 
191e857
6334b6a
 
 
 
 
 
 
 
9ed529e
 
6334b6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
947f818
 
 
45d005b
 
6334b6a
 
ec8e0a8
869d534
 
9ed529e
cddd89d
869d534
6334b6a
 
869d534
 
 
 
 
 
 
 
 
 
 
 
 
 
6334b6a
 
869d534
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ed529e
cddd89d
6334b6a
9ed529e
45d005b
9ed529e
 
45d005b
 
cddd89d
9ed529e
 
 
 
 
45d005b
 
 
 
 
 
 
 
6334b6a
45d005b
 
 
 
 
 
 
 
 
 
 
 
9ed529e
45d005b
 
 
 
947f818
 
 
 
45d005b
947f818
6334b6a
9ed529e
45d005b
 
 
947f818
 
6334b6a
 
 
 
 
947f818
6334b6a
947f818
 
6334b6a
 
 
 
 
 
 
 
 
45d005b
 
 
 
 
947f818
45d005b
 
 
 
 
 
 
 
 
 
947f818
1d44344
4a7df61
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
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_canvas_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.
 """


system_prompt_canvas_2 = """
You are a film screen writer, who will be acting as a co-writer whose main objective is to 
help create a beat sheet in which every beat answers minimum of below 3 questions:
1. Who is there in the scene?
2. Where are they?
3. What is the conflict?

Process:
- Ask user what is the opening scene of their film.
- Next, ask user what scenes would they like to show for the entire act 1, leading upto the inciting incident beat.
- Now, develop detailed beat for every scene that user just shared for Act 1.
- Repeat the process for Act 2 and Act 3.
- Next, make sure the high level beats do infact connect in a coherent way

Once you have all the beats which are foundation for writing scenes in the screenplay, present them to
the user in a single space format 
Have the user review all the beats and confirm if they are happy with the beats or if they want to make further changes

RULES:
- Ask only one question at a time.

The below conversation happened between user and an expert screen writer assistant so far where user and their screen writer assistant came up with
a high level story outline, and key Story Beats:
"""


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"""

    print ("HISTORY:"+str(history))
    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 ""
        }

        print("FORMATTED:"+str(formatted_history))
        
        # 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_canvas_1})
    history.append({"role": "user", "content": message})
    print ("-----------------------------FIRST PROMPT", history)
    stream = client.chat.completions.create(
        messages=history, 
        model="Meta-Llama-3.1-70B-Instruct-8k", 
        # model ="Meta-Llama-3.3-70B-Instruct",
        temperature= 0.8,
        stream=True
        )
    chunks = []
    for chunk in stream:
        chunks.append(chunk.choices[0].delta.content or "")
        yield "".join(chunks)

def predict_beat_sheet(message, history_beatsheet, canvas_1_context):
    # print ("canvas_1_context:", canvas_1_context)
    system_prompt = f"{system_prompt_canvas_2}\n ### {canvas_1_context} ###"
    # system_prompt = f"{system_prompt_canvas_2}"
    history_beatsheet.append({"role": "system", "content": system_prompt})
    history_beatsheet.append({"role": "user", "content": message})

    print ("-----------------------------ALL TOEGTEHER PROMPT", history_beatsheet)
    stream = client.chat.completions.create(
        messages=history_beatsheet, 
        model="Meta-Llama-3.1-70B-Instruct-8k", 
        # model ="Meta-Llama-3.3-70B-Instruct",
        temperature= 0.8,
        stream=True
        )

    chunks = []
    for chunk in stream:
        chunks.append(chunk.choices[0].delta.content or "")
        yield "".join(chunks)
    # return "HHAHAHA"


def show_beat_sheet(canvas_1_history):
    # Extracting the content values
    content_list = [entry['content'] for entry in canvas_1_history if 'content' in entry]
    
    inference_output = content_list[-1]
    canvas_1_context= str(canvas_1_history)
    return gr.update(visible= True), inference_output, canvas_1_context

with gr.Blocks(fill_height=True) as demo:
    canvas_1_context = gr.Textbox(label="canvas_1_context_stuff", render= False)
    with gr.Column() as train_section:
        # gr.Markdown("## Train")
        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"
        )
        # feedback= gr.Textbox(label = "Feedback", placeholder = "Help us make scripti better, provide feedback here..") # render = False
        # btn = gr.Button(value="Share feedback") # render= False
        
        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])

        create_beatsheet_button = gr.Button("Create Beat sheet")
    
    with gr.Column(visible=False) as inference_section:
        gr.Markdown("## Beat sheet")
        inference_output = gr.Textbox(label="Inference Output")
        # canvas_1_context.render()
        # print("Anything here:",inference_output.value)
        chatinterface_beatsheet = gr.ChatInterface(
            predict_beat_sheet, 
            type="messages",
            title="scripti_beatsheet",
            examples=[[{"text": "Lets write beat today"}]],
            show_progress="full",
            additional_inputs=[canvas_1_context]
        )
       
    create_beatsheet_button.click(fn=show_beat_sheet, inputs= [chatinterface.chatbot], outputs=[inference_section, inference_output, canvas_1_context])
demo.launch()