fmmkii commited on
Commit
12671eb
Β·
1 Parent(s): 95a72ab

Revamped API handling

Browse files
Files changed (6) hide show
  1. __pycache__/generate_script.cpython-313.pyc +0 -0
  2. app.py +14 -10
  3. imggen.py +10 -15
  4. manual.py +1 -1
  5. scriptgen.py +10 -12
  6. tweaker.py +19 -16
__pycache__/generate_script.cpython-313.pyc CHANGED
Binary files a/__pycache__/generate_script.cpython-313.pyc and b/__pycache__/generate_script.cpython-313.pyc differ
 
app.py CHANGED
@@ -1,12 +1,13 @@
1
  import streamlit as st
2
- from dotenv import load_dotenv, set_key
3
  import os
 
4
 
5
  # Load environment variables from .env file
6
  load_dotenv()
7
 
8
  st.set_page_config(layout='wide', page_icon='✨')
9
 
 
10
  scriptgen = st.Page("scriptgen.py", title="Script Generator", icon='πŸ“ƒ')
11
  imggen = st.Page("imggen.py", title="Thumbnail Generator", icon='πŸ–ΌοΈ')
12
  tweaker = st.Page("tweaker.py", title="Creative Consultant", icon='🎬')
@@ -14,27 +15,30 @@ jsonbase = st.Page("secretary.py", title="Script Secretary", icon='πŸ“š')
14
  manual = st.Page("manual.py", title="Manual", icon="πŸ‘“", default=True)
15
  docs = st.Page("docs.py", title="Documentation", icon='πŸ“‘')
16
 
17
- # Check if OPENAI_API_KEY exists in the environment
18
- api_key = os.getenv('OPENAI_API_KEY', None) # Fallback to None if not found
19
-
20
  # Sidebar for API Key input and options
21
  with st.sidebar:
22
  api_key_input = st.text_input('Enter your OpenAI API token:', type='password')
23
 
24
  if st.button("Save API Key"):
25
  if api_key_input.startswith("sk-"): # Basic validation
 
 
 
26
  env_file = ".env"
27
- set_key(env_file, "OPENAI_API_KEY", api_key_input) # Save to .env
28
  st.success("API Key saved successfully!")
29
  else:
30
  st.error("Invalid API Key format!")
31
 
32
- # Check and display the status of the API key
33
- if api_key:
34
- st.success("API Key loaded from environment!")
35
- else:
36
- st.warning("No API Key found. Please enter one.")
 
 
37
 
 
38
  pg = st.navigation(
39
  {
40
  "Others": [manual, docs],
 
1
  import streamlit as st
 
2
  import os
3
+ from dotenv import load_dotenv, set_key
4
 
5
  # Load environment variables from .env file
6
  load_dotenv()
7
 
8
  st.set_page_config(layout='wide', page_icon='✨')
9
 
10
+ # Create pages
11
  scriptgen = st.Page("scriptgen.py", title="Script Generator", icon='πŸ“ƒ')
12
  imggen = st.Page("imggen.py", title="Thumbnail Generator", icon='πŸ–ΌοΈ')
13
  tweaker = st.Page("tweaker.py", title="Creative Consultant", icon='🎬')
 
15
  manual = st.Page("manual.py", title="Manual", icon="πŸ‘“", default=True)
16
  docs = st.Page("docs.py", title="Documentation", icon='πŸ“‘')
17
 
 
 
 
18
  # Sidebar for API Key input and options
19
  with st.sidebar:
20
  api_key_input = st.text_input('Enter your OpenAI API token:', type='password')
21
 
22
  if st.button("Save API Key"):
23
  if api_key_input.startswith("sk-"): # Basic validation
24
+ # Save API key to session state
25
+ st.session_state["OPENAI_API_KEY"] = api_key_input
26
+ # Optionally, save it to .env file or any persistent storage
27
  env_file = ".env"
28
+ set_key(env_file, "OPENAI_API_KEY", api_key_input)
29
  st.success("API Key saved successfully!")
30
  else:
31
  st.error("Invalid API Key format!")
32
 
33
+ # Check if API Key is available
34
+ api_key = st.session_state.get("OPENAI_API_KEY", None)
35
+
36
+ if api_key:
37
+ st.success("API Key loaded from session!")
38
+ else:
39
+ st.warning("No API Key found. Please enter one.")
40
 
41
+ # Example navigation setup for your pages
42
  pg = st.navigation(
43
  {
44
  "Others": [manual, docs],
imggen.py CHANGED
@@ -1,40 +1,35 @@
1
  import streamlit as st
2
  from openai import OpenAI
3
  import time
4
- from dotenv import load_dotenv
5
  import os
6
  import requests
7
  from io import BytesIO
8
  from PIL import Image
9
  import json
10
 
11
- # Load environment variables
12
- load_dotenv()
13
-
14
  # Initialize OpenAI client
15
  client = OpenAI()
16
 
 
 
 
 
 
 
 
 
17
  # Load script history
18
  history_file = "script_history.json"
19
 
20
-
21
  def load_script_history():
22
  if os.path.exists(history_file):
23
  with open(history_file, "r") as file:
24
  return json.load(file)
25
  return []
26
 
27
-
28
  script_history = load_script_history()
29
 
30
- # Retrieve the API key
31
- api_key = os.getenv("OPENAI_API_KEY")
32
-
33
- if not api_key:
34
- st.error("API Key not provided! Please add it to Streamlit secrets or the .env file.")
35
- else:
36
- os.environ['OPENAI_API_KEY'] = api_key # Set the API key for OpenAI
37
-
38
  # Initialize session state for image history
39
  if "image_history" not in st.session_state:
40
  st.session_state.image_history = []
@@ -71,7 +66,7 @@ with left_col:
71
  styles = st.multiselect(
72
  "Image artstyle",
73
  [
74
- 'Realism', 'Impressionism','Cubism', 'Surrealism', 'Baroque', 'Art Noveau', 'Cyberpunk',
75
  'Synthwave', 'Anime', 'Pixel Art', 'Low Poly', 'Dark Fantasy', 'Space Opera',
76
  'Steampunk', 'Fantasy', 'Abstract', 'Glitch Art', 'Kawaii', 'Pop Art'
77
  ],
 
1
  import streamlit as st
2
  from openai import OpenAI
3
  import time
4
+ from dotenv import load_dotenv, set_key
5
  import os
6
  import requests
7
  from io import BytesIO
8
  from PIL import Image
9
  import json
10
 
 
 
 
11
  # Initialize OpenAI client
12
  client = OpenAI()
13
 
14
+ # Get the API key from session state (which is set in app.py)
15
+ api_key = st.session_state.get("OPENAI_API_KEY", None)
16
+
17
+ if not api_key:
18
+ st.error("API Key not provided! Please enter it in the main app.")
19
+ else:
20
+ os.environ['OPENAI_API_KEY'] = api_key # Set the API key for OpenAI
21
+
22
  # Load script history
23
  history_file = "script_history.json"
24
 
 
25
  def load_script_history():
26
  if os.path.exists(history_file):
27
  with open(history_file, "r") as file:
28
  return json.load(file)
29
  return []
30
 
 
31
  script_history = load_script_history()
32
 
 
 
 
 
 
 
 
 
33
  # Initialize session state for image history
34
  if "image_history" not in st.session_state:
35
  st.session_state.image_history = []
 
66
  styles = st.multiselect(
67
  "Image artstyle",
68
  [
69
+ 'Realism', 'Impressionism', 'Cubism', 'Surrealism', 'Baroque', 'Art Noveau', 'Cyberpunk',
70
  'Synthwave', 'Anime', 'Pixel Art', 'Low Poly', 'Dark Fantasy', 'Space Opera',
71
  'Steampunk', 'Fantasy', 'Abstract', 'Glitch Art', 'Kawaii', 'Pop Art'
72
  ],
manual.py CHANGED
@@ -5,7 +5,7 @@ st.write('''Powered with OpenAI, this toolkit helps you create scripts and thumb
5
  ''')
6
 
7
  st.subheader("1. Things you need before you begin")
8
- st.markdown("Please make sure you have your **OpenAI API Key** ready to be able to use this toolkit. If none provided, you may be prompted to enter the **API Key**. You may visit the OpenAI for you to retrieve your **API Key**." )
9
  st.info("Please take note that using the API also requires additional payment")
10
 
11
  st.subheader('2. Script Generator')
 
5
  ''')
6
 
7
  st.subheader("1. Things you need before you begin")
8
+ st.markdown("Please make sure you have your **OpenAI API Key** ready to be able to use this toolkit. If none provided, you may be prompted to enter the **API Key**. You may visit the OpenAI for you to retrieve your **API Key**. After entering, click the **Save API Key** to begin")
9
  st.info("Please take note that using the API also requires additional payment")
10
 
11
  st.subheader('2. Script Generator')
scriptgen.py CHANGED
@@ -1,27 +1,25 @@
1
  import streamlit as st
2
- from dotenv import load_dotenv
3
  from generate_script import generate_script
4
  import os
5
  import json
6
 
7
- # File to store script history
8
- history_file = "script_history.json"
9
-
10
- # Load environment variables from .env file
11
  load_dotenv()
12
 
13
- st.title("Script Generator πŸ“ƒ")
14
- st.subheader("Create your script with just a single prompt!")
15
-
16
- # Retrieve API key from secrets or environment variables
17
- api_key = os.getenv("OPENAI_API_KEY")
18
- serper_api_key = os.getenv("SERPER_API_KEY")
19
 
 
20
  if not api_key:
21
- st.error("Please provide a valid API Key in Streamlit secrets or .env file.")
22
  else:
23
  os.environ["OPENAI_API_KEY"] = api_key
24
 
 
 
 
25
  # Function to load history from file
26
  def load_history():
27
  if os.path.exists(history_file):
 
1
  import streamlit as st
2
+ from dotenv import load_dotenv, set_key
3
  from generate_script import generate_script
4
  import os
5
  import json
6
 
7
+ # Load environment variables
 
 
 
8
  load_dotenv()
9
 
10
+ # Initialize the API key
11
+ api_key = st.session_state.get("OPENAI_API_KEY", None)
12
+ serper_api_key = st.secrets.get("SERPER_API_KEY")
 
 
 
13
 
14
+ # Check if API keys are available
15
  if not api_key:
16
+ st.error("API Key not provided! Please enter it in the main app.")
17
  else:
18
  os.environ["OPENAI_API_KEY"] = api_key
19
 
20
+ # File to store script history
21
+ history_file = "script_history.json"
22
+
23
  # Function to load history from file
24
  def load_history():
25
  if os.path.exists(history_file):
tweaker.py CHANGED
@@ -6,6 +6,14 @@ from langchain.chains import ConversationChain
6
  from langchain.memory import ConversationSummaryMemory
7
  from langchain.prompts import ChatPromptTemplate
8
 
 
 
 
 
 
 
 
 
9
  st.title('Creative Consultant 🎬')
10
  st.subheader('Ask content creation tips or help tweak your premade script!')
11
 
@@ -25,34 +33,27 @@ if "messages" not in st.session_state:
25
  ]
26
  if "conversation" not in st.session_state:
27
  st.session_state["conversation"] = None
28
- if "OPENAI_API_KEY" not in st.session_state:
29
- st.session_state["OPENAI_API_KEY"] = ""
30
 
31
  def clear_chat_history():
32
  st.session_state.messages = [{"role": "assistant", "content": "Chat history cleared. What would you like help with next?"}]
33
 
34
-
35
-
36
  # Load generated scripts from history
37
  script_history = load_script_history()
38
 
39
  # Sidebar for script selection
 
40
  if script_history:
41
  st.sidebar.header("Previously Generated Scripts")
42
-
43
- # Add "Other" option to the list of scripts
44
  script_titles = [f"Script {idx + 1}: {item['title']}" for idx, item in enumerate(script_history)]
45
  script_titles.append("Other") # Add "Other" as an option
46
-
47
- # Let the user select a script or "Other"
48
  selected_script_idx = st.sidebar.selectbox(
49
  "Choose a script to tweak:",
50
  range(len(script_titles)),
51
  format_func=lambda x: script_titles[x]
52
  )
53
 
54
- # If "Other" is chosen
55
- if selected_script_idx == len(script_titles) - 1:
56
  st.sidebar.text_area(
57
  "Free Conversation or Custom Tweaking",
58
  placeholder="Write your thoughts or tweaks here...",
@@ -60,8 +61,7 @@ if script_history:
60
  key="free_conversation"
61
  )
62
  else:
63
- # Display the selected script
64
- selected_script = script_history[selected_script_idx]
65
  st.sidebar.text_area(
66
  "Script Content",
67
  value=selected_script["script"],
@@ -71,7 +71,6 @@ if script_history:
71
  else:
72
  st.sidebar.info("No scripts available. Please generate scripts using the Script Generator.")
73
 
74
-
75
  st.sidebar.button('Clear Chat History', on_click=clear_chat_history)
76
 
77
  # Prompt template for the Creative Consultant
@@ -96,7 +95,7 @@ def get_response(user_input):
96
  llm = ChatOpenAI(
97
  model='gpt-4o-mini',
98
  temperature=0.1,
99
- max_tokens=512,
100
  timeout=None,
101
  max_retries=2
102
  )
@@ -125,7 +124,7 @@ if user_input:
125
 
126
  try:
127
  # Use the selected script as context for the assistant's response
128
- if script_history:
129
  user_input_with_context = f"""
130
  The user selected the following script for feedback:
131
  Title: {selected_script['title']}
@@ -134,7 +133,11 @@ if user_input:
134
  User's query: {user_input}
135
  """
136
  else:
137
- user_input_with_context = user_input
 
 
 
 
138
 
139
  # Generate the assistant's response
140
  with st.spinner():
 
6
  from langchain.memory import ConversationSummaryMemory
7
  from langchain.prompts import ChatPromptTemplate
8
 
9
+ # Get the API key from session state (which was set in app.py)
10
+ api_key = st.session_state.get("OPENAI_API_KEY", None)
11
+
12
+ if not api_key:
13
+ st.error("API Key not provided! Please enter it in the main app.")
14
+ else:
15
+ os.environ['OPENAI_API_KEY'] = api_key # Set the API key for OpenAI
16
+
17
  st.title('Creative Consultant 🎬')
18
  st.subheader('Ask content creation tips or help tweak your premade script!')
19
 
 
33
  ]
34
  if "conversation" not in st.session_state:
35
  st.session_state["conversation"] = None
 
 
36
 
37
  def clear_chat_history():
38
  st.session_state.messages = [{"role": "assistant", "content": "Chat history cleared. What would you like help with next?"}]
39
 
 
 
40
  # Load generated scripts from history
41
  script_history = load_script_history()
42
 
43
  # Sidebar for script selection
44
+ selected_script = None
45
  if script_history:
46
  st.sidebar.header("Previously Generated Scripts")
 
 
47
  script_titles = [f"Script {idx + 1}: {item['title']}" for idx, item in enumerate(script_history)]
48
  script_titles.append("Other") # Add "Other" as an option
 
 
49
  selected_script_idx = st.sidebar.selectbox(
50
  "Choose a script to tweak:",
51
  range(len(script_titles)),
52
  format_func=lambda x: script_titles[x]
53
  )
54
 
55
+ if selected_script_idx == len(script_titles) - 1: # Free Conversation selected
56
+ selected_script = None # No specific script is selected
57
  st.sidebar.text_area(
58
  "Free Conversation or Custom Tweaking",
59
  placeholder="Write your thoughts or tweaks here...",
 
61
  key="free_conversation"
62
  )
63
  else:
64
+ selected_script = script_history[selected_script_idx] # Fetch the selected script
 
65
  st.sidebar.text_area(
66
  "Script Content",
67
  value=selected_script["script"],
 
71
  else:
72
  st.sidebar.info("No scripts available. Please generate scripts using the Script Generator.")
73
 
 
74
  st.sidebar.button('Clear Chat History', on_click=clear_chat_history)
75
 
76
  # Prompt template for the Creative Consultant
 
95
  llm = ChatOpenAI(
96
  model='gpt-4o-mini',
97
  temperature=0.1,
98
+ max_tokens=None,
99
  timeout=None,
100
  max_retries=2
101
  )
 
124
 
125
  try:
126
  # Use the selected script as context for the assistant's response
127
+ if selected_script:
128
  user_input_with_context = f"""
129
  The user selected the following script for feedback:
130
  Title: {selected_script['title']}
 
133
  User's query: {user_input}
134
  """
135
  else:
136
+ user_input_with_context = f"""
137
+ Free conversation mode. The user has not selected a script.
138
+
139
+ User's query: {user_input}
140
+ """
141
 
142
  # Generate the assistant's response
143
  with st.spinner():