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