DrishtiSharma commited on
Commit
6d07543
·
verified ·
1 Parent(s): dfaa012

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -66
app.py CHANGED
@@ -5,102 +5,98 @@ import streamlit as st
5
  from graph import EssayWriter
6
  import os
7
  import base64
8
- from readability import Readability
9
 
10
- # Set up the page configuration
11
- st.set_page_config(page_title="Multi-Agent Essay Writer", page_icon="✍️", layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- # Initialize session state variables
14
  if "messages" not in st.session_state:
15
- st.session_state.messages = [{"role": "assistant", "content": "Hello! How can I assist you with your essay?"}]
16
  st.session_state.app = None
17
  st.session_state.chat_active = True
18
- st.session_state.saved_essays = {}
19
 
20
- # Sidebar for settings and initialization
21
  with st.sidebar:
22
- st.title("Settings")
23
- st.info("🔑 Provide your OpenAI API key to enable functionality.")
 
24
  developer_mode = st.checkbox("Developer Mode", value=False)
25
- openai_key = st.secrets.get("OPENAI_API_KEY", "") if not developer_mode else st.text_input("OpenAI API Key", type="password")
26
 
27
- if st.button("Initialize AI Agents"):
28
- if len(openai_key) > 0:
29
- os.environ["OPENAI_API_KEY"] = openai_key
30
- st.session_state.app = EssayWriter()
31
- st.success("Agents initialized successfully!")
32
- st.session_state.chat_active = False
33
- else:
34
- st.error("OpenAI API key is missing! Please provide a valid key.")
 
 
 
 
 
 
 
 
 
35
 
36
- # Display saved essays for easy access
37
- st.markdown("### Saved Essays")
38
- for title, content in st.session_state.saved_essays.items():
39
- if st.button(f"Load Essay: {title}"):
40
- st.session_state.messages.append({"role": "assistant", "content": f"Loaded Essay: {title}"})
41
- st.session_state.loaded_essay = content
42
 
43
- # Function to generate AI responses
44
  def generate_response(topic):
45
- if st.session_state.app:
46
- return st.session_state.app.graph.invoke({"topic": topic})
47
- return {"response": "Error: AI agents are not initialized."}
48
 
49
- # Display chat history
50
  for message in st.session_state.messages:
51
  with st.chat_message(message["role"]):
52
  st.markdown(message["content"], unsafe_allow_html=True)
53
 
54
- # Chat input for user queries
55
- response = None
56
- if topic := st.chat_input(placeholder="Ask me to write, edit, format, or analyze an essay!"):
57
  st.chat_message("user").markdown(topic)
58
  st.session_state.messages.append({"role": "user", "content": topic})
59
 
60
- with st.spinner("Processing your request..."):
61
  response = generate_response(topic)
62
 
63
  with st.chat_message("assistant"):
64
- if response and "pdf_name" in response:
65
  with open(f"./{response['pdf_name']}", "rb") as file:
66
  file_bytes = file.read()
67
  b64 = base64.b64encode(file_bytes).decode()
68
- href = f"<a href='data:application/octet-stream;base64,{b64}' download='{response['pdf_name']}'>Download Your Essay</a>"
69
- st.markdown(f"{response['response']} {href}", unsafe_allow_html=True)
70
- st.session_state.messages.append({"role": "assistant", "content": f"{response['response']} {href}"})
71
- elif response:
72
  st.markdown(response["response"])
73
  st.session_state.messages.append({"role": "assistant", "content": response["response"]})
74
- else:
75
- st.error("Failed to process your request. Please try again.")
76
-
77
- # Save the essay for future reference
78
- if response and "essay" in response:
79
- save_title = st.text_input("Save this essay as:", value="Untitled Essay")
80
- if st.button("Save Essay"):
81
- st.session_state.saved_essays[save_title] = response["essay"]
82
- st.success(f"Essay saved as '{save_title}'.")
83
-
84
- # Add readability analysis for the generated essay
85
- if response and "essay" in response:
86
- st.markdown("---")
87
- st.markdown("### Essay Analysis")
88
-
89
- essay_text = response["essay"]
90
- r = Readability(essay_text)
91
- try:
92
- flesch_score = r.flesch()
93
- st.metric("Flesch Reading Ease", f"{flesch_score.score:.2f}")
94
- except Exception:
95
- st.warning("Could not calculate readability. The essay may not be in a valid format.")
96
 
97
- # Footer for acknowledgments
98
  st.markdown("---")
99
  st.markdown(
100
  """
101
- <div style="text-align: center; font-size: 12px; color: #777;">
102
- <strong>Multi-Agent Essay Writer:</strong> A tool for writing, editing, and analyzing essays.
 
 
 
 
103
  </div>
104
- """,
105
- unsafe_allow_html=True,
106
- )
 
5
  from graph import EssayWriter
6
  import os
7
  import base64
 
8
 
9
+ st.set_page_config(page_title="Multi-Agent Essay Writer", page_icon="🤖")
10
+
11
+ button_html = f'''
12
+ <div style="display: flex; justify-content: center;">
13
+ <a href=" " target="_blank">
14
+ <button style="
15
+ background-color: #FFDD00;
16
+ border: none;
17
+ color: black;
18
+ padding: 10px 20px;
19
+ text-align: center;
20
+ text-decoration: none;
21
+ display: inline-block;
22
+ font-size: 16px;
23
+ margin: 4px 2px;
24
+ cursor: pointer;
25
+ border-radius: 10px;
26
+ box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2);
27
+ ">
28
+ </button>
29
+ </a>
30
+ </div>
31
+ '''
32
 
 
33
  if "messages" not in st.session_state:
34
+ st.session_state.messages = [{"role": "assistant", "content": "Hello!"}]
35
  st.session_state.app = None
36
  st.session_state.chat_active = True
 
37
 
 
38
  with st.sidebar:
39
+ st.info(" * This app uses the OpenAI API to generate text, please provide your API key."
40
+ "\n\n * This app uses the 'gpt-4o-mini-2024-07-18' model. Cost effective and efficient."
41
+ "\n\n * Writing essays may take some time, please be patient. Approximately 1-2 minutes.")
42
  developer_mode = st.checkbox("Developer Mode", value=False)
43
+ openai_key = st.secrets.get("OPENAI_API_KEY", "") if not developer_mode else st.text_input("OpenAI API Key (Developer Mode)", type="password")
44
 
45
+ def initialize_agents():
46
+ if len(openai_key) < 1:
47
+ st.error("OpenAI API key is missing! Please provide a valid key through Hugging Face Secrets.")
48
+ st.session_state.chat_active = True
49
+ return None
50
+
51
+ os.environ["OPENAI_API_KEY"] = openai_key
52
+ essay_writer = EssayWriter().graph
53
+ st.success("Agents successfully initialized!")
54
+ st.session_state.chat_active = False
55
+ return essay_writer
56
+
57
+ with st.sidebar:
58
+ if st.button("Initialize Agents", type="primary"):
59
+ st.session_state.app = initialize_agents()
60
+ st.divider()
61
+ st.markdown(button_html, unsafe_allow_html=True)
62
 
63
+ app = st.session_state.app
 
 
 
 
 
64
 
 
65
  def generate_response(topic):
66
+ return app.invoke(input={"topic": topic}) if app else {"response": "Error: Agents not initialized."}
 
 
67
 
 
68
  for message in st.session_state.messages:
69
  with st.chat_message(message["role"]):
70
  st.markdown(message["content"], unsafe_allow_html=True)
71
 
72
+ if topic := st.chat_input(placeholder="Ask a question", disabled=st.session_state.chat_active):
 
 
73
  st.chat_message("user").markdown(topic)
74
  st.session_state.messages.append({"role": "user", "content": topic})
75
 
76
+ with st.spinner("Thinking..."):
77
  response = generate_response(topic)
78
 
79
  with st.chat_message("assistant"):
80
+ if "pdf_name" in response:
81
  with open(f"./{response['pdf_name']}", "rb") as file:
82
  file_bytes = file.read()
83
  b64 = base64.b64encode(file_bytes).decode()
84
+ href = f"<a href='data:application/octet-stream;base64,{b64}' download='{response['pdf_name']}'>Click here to download the PDF</a>"
85
+ st.markdown(f"{response['response']}: {href}", unsafe_allow_html=True)
86
+ st.session_state.messages.append({"role": "assistant", "content": f"{response['response']}: {href}"})
87
+ else:
88
  st.markdown(response["response"])
89
  st.session_state.messages.append({"role": "assistant", "content": response["response"]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
+ # Add acknowledgment at the bottom
92
  st.markdown("---")
93
  st.markdown(
94
  """
95
+ <div style="text-align: center; font-size: 14px; color: #555;">
96
+ <strong>Acknowledgment:</strong> This project is based on Mesut Duman's work:
97
+ <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
98
+ target="_blank" style="color: #007BFF; text-decoration: none;">
99
+ CrewAI Essay Writer
100
+ </a>
101
  </div>
102
+ """, unsafe_allow_html=True)