Spaces:
Sleeping
Sleeping
Download app.py from kaurdotai/scripti_sandbox: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/spaces/kaurdotai/scripti_sandbox/resolve/main/app.py
- Command line
-
hf download hf://spaces/kaurdotai/scripti_sandbox/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kaurdotai/scripti_sandbox/resolve/main/app.py
14 kB
| 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() | |