-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
197 lines (159 loc) · 6.71 KB
/
app.py
File metadata and controls
197 lines (159 loc) · 6.71 KB
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
import streamlit as st
from src.workflow import create_workflow
import json
def initialize_session_state():
if 'history' not in st.session_state:
st.session_state.history = []
if 'current_email' not in st.session_state:
st.session_state.current_email = None
if 'current_response' not in st.session_state:
st.session_state.current_response = None
if 'response_counter' not in st.session_state:
st.session_state.response_counter = 0
def display_header():
st.title("✉️ Email Response Generator")
def display_input_section():
with st.container():
st.markdown('<p class="section-title">📝 Input Email</p>', unsafe_allow_html=True)
email_content = st.text_area(
label="",
placeholder="""Hi, Subhranil!
I am Subhranil Mondal, the owner of this tool. Feel free to review my tool.
Have fun!
The CheapCodderz Team""",
height=400,
key="email_input"
)
generate_button = st.button(
"🚀 Generate Response",
key="generate_button",
use_container_width=True,
type="primary"
)
if st.session_state.history:
with st.expander("📚 Previous Emails", expanded=False):
for idx, item in enumerate(st.session_state.history):
st.text_area(
f"Email {idx + 1}",
item["email"],
height=400,
key=f"history_email_{idx}"
)
st.markdown("---")
return email_content, generate_button
def extract_email_draft(response_text: str) -> str:
"""Extract email draft from the response text."""
try:
if isinstance(response_text, str):
try:
json_response = json.loads(response_text)
if isinstance(json_response, dict) and 'email_draft' in json_response:
return json_response['email_draft']
except json.JSONDecodeError:
pass
if '"email_draft":' in response_text:
start_idx = response_text.find('"email_draft":') + len('"email_draft":')
content_start = response_text.find('"', start_idx) + 1
content_end = response_text.rfind('"')
if content_start < content_end:
return response_text[content_start:content_end]
return response_text
except Exception as e:
print(f"Error extracting email draft: {e}")
return response_text
def process_email(email_content):
try:
with st.spinner("🔄 Processing your email..."):
app = create_workflow()
inputs = {
"initial_email": email_content,
"research_info": None,
"num_steps": 0
}
output = app.invoke(inputs)
response = output.get('draft_email', 'Unable to process email')
clean_response = extract_email_draft(response)
return clean_response, None
except Exception as e:
return None, str(e)
def display_response_section(response, is_new=False):
if is_new:
st.session_state.response_counter += 1
response_id = st.session_state.response_counter
if response:
st.markdown('<p class="section-title">📨 Generated Response</p>', unsafe_allow_html=True)
tabs = st.tabs(["✏️ Editor", "👀 Preview", "💾 Drafts"])
with tabs[0]:
edited_response = st.text_area(
label="",
value=response,
height=400,
key=f"response_editor_{response_id}"
)
col1, col2 = st.columns(2)
with col1:
if st.button("📋 Copy to Clipboard",
key=f"copy_{response_id}",
use_container_width=True):
st.toast("Response copied to clipboard! 📋")
with col2:
if st.button("💾 Save Draft",
key=f"save_{response_id}",
use_container_width=True):
st.session_state.history.append({
"email": st.session_state.current_email,
"response": edited_response
})
st.toast("Draft saved! 💾")
with tabs[1]:
st.markdown(f"""<div style="background-color: #2D2D2D; padding: 20px; border-radius: 8px; border: 1px solid #404040;">
<pre style="color: #FFFFFF; margin: 0;">{response}</pre>
</div>""", unsafe_allow_html=True)
with tabs[2]:
if st.session_state.history:
for idx, item in enumerate(reversed(st.session_state.history)):
with st.expander(f"Draft {len(st.session_state.history) - idx}", expanded=False):
st.text_area(
"Response",
item["response"],
height=200,
key=f"draft_response_{response_id}_{idx}"
)
else:
st.info("No saved drafts yet!")
def main():
st.set_page_config(
page_title="AI ER Agent",
page_icon="✉️",
layout="wide",
initial_sidebar_state="collapsed",
menu_items={
'Get help': None,
'Report a bug': None,
'About': None
}
)
initialize_session_state()
display_header()
col1, col2 = st.columns([4, 5])
with col1:
st.markdown('<div class="content-box">', unsafe_allow_html=True)
email_content, generate_clicked = display_input_section()
st.markdown('</div>', unsafe_allow_html=True)
with col2:
st.markdown('<div class="content-box">', unsafe_allow_html=True)
if generate_clicked and email_content:
st.session_state.current_email = email_content
response, error = process_email(email_content)
if error:
st.error(f"❌ An error occurred: {error}")
else:
st.session_state.current_response = response
display_response_section(response, is_new=True)
elif st.session_state.current_response:
display_response_section(st.session_state.current_response)
else:
st.info("Generate a response to see it here!")
st.markdown('</div>', unsafe_allow_html=True)
if __name__ == "__main__":
main()