wolf1997 commited on
Commit
1579f32
·
verified ·
1 Parent(s): 6bb248e

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -348
app.py DELETED
@@ -1,348 +0,0 @@
1
- import streamlit as st
2
- import pandas as pd
3
- from main_agent import Main_agent
4
- import asyncio
5
- import tempfile
6
- import os
7
- from PIL import Image
8
- from io import BytesIO
9
- import requests
10
- from spire.doc import Document, FileFormat
11
- import nest_asyncio
12
- import platform
13
- from dataclasses import dataclass
14
-
15
- # Apply nest_asyncio to allow nested event loops
16
- nest_asyncio.apply()
17
-
18
- # Create event loop
19
- if platform.system() == 'Windows':
20
- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
21
-
22
- test_data={'title': 'Sunday App and Stripe: A Payment Strategy for Restaurants',
23
- 'image_url': 'https://www.menutiger.com/_next/image?url=http%3A%2F%2Fcms.menutiger.com%2Fwp-content%2Fuploads%2F2023%2F07%2Fseamless-stripe-payment-integration-for-restaurants-2.jpg&w=2048&q=75',
24
- 'paragraphs': [{'title': 'Introduction',
25
- 'content': 'Sunday is a payment solution designed to streamline the restaurant experience. Co-founded in April 2021 by Christine de Wendel, Victor Lugger, and Tigrane Seydoux, it aims to address inefficiencies in the restaurant industry by simplifying payments through QR code technology, allowing customers to quickly access their bill, split it, add a tip, and pay in seconds. Integrated with existing POS systems and partnering with payment providers like Stripe and Checkout.com, Sunday also offers features such as digital menus with customizable options, order and pay capabilities, and tools to enhance online reputation and customer engagement for restaurants.'},
26
- {'title': "Sunday's Payment Strategy",
27
- 'content': "Sunday's payment strategy focuses on streamlining the payment process in restaurants through its QR code-based system, enabling customers to pay quickly and efficiently. This approach not only simplifies payments but also reduces processing fees for restaurants through partnerships with companies like Stripe and Checkout.com. The company's payment solution is designed to integrate seamlessly with existing POS systems, offering additional features such as digital menus, order and pay capabilities, and tools to improve online reputation and customer engagement."},
28
- {'title': 'Partnership with Stripe',
29
- 'content': 'On Wednesday, Sunday announced its new Order & Pay capabilities and its partnership with Stripe, which has allowed it to reduce processing fees for restaurants by an average of 0.5%. Through Stripe, Sunday processes payments via a QR code at the table, which allows customers to pay, split the bill, and add a tip quickly. Sunday is also negotiating with payment providers for better rates.'},
30
- {'title': 'Stripe Integration and Fee Reduction',
31
- 'content': 'Sunday leverages Stripe to process payments, utilizing a QR code system for customer convenience. This partnership has enabled Sunday to reduce processing fees for restaurants by an average of 0.5%.'},
32
- {'title': 'Benefits for Restaurants',
33
- 'content': 'Sunday offers numerous benefits for restaurants by leveraging its technology and partnerships, including Stripe. Restaurants using Sunday can experience increased efficiency through streamlined payment processes and order and pay capabilities. Sunday also helps restaurants collect valuable data and analytics, including customer insights and business analytics, which can be used to improve operations and enhance customer experience. Additionally, the integration with Stripe reduces processing fees, benefiting restaurant finances.'},
34
- {'title': 'Conclusion',
35
- 'content': 'In conclusion, Sunday has significantly impacted restaurant payments by streamlining the payment process and reducing processing fees through its partnership with Stripe. This collaboration has enabled restaurants to enhance efficiency, improve customer experiences, and gain valuable data insights, positioning Sunday as a key player in revolutionizing the restaurant industry.'}],
36
- 'table': {'data': [['App Functionality',
37
- 'Access bill and pay in two clicks, browse the full menu.'],
38
- ['Payment Processing', 'Payments processed by Stripe.'],
39
- ['Stripe Agreement Benefit',
40
- 'Reduced processing fees for restaurants by an average of 0.5%.'],
41
- ['Restaurant Benefits',
42
- 'More tips, more reviews, and more data for restaurants. Increased order and average basket size.'],
43
- ['Point of Sale Integration',
44
- 'Works seamlessly with existing POS systems.'],
45
- ['Payment Method', 'Guests scan a QR code to pay.'],
46
- ['Additional Features',
47
- 'Digital menu with customizable features (scheduling, tags, extras). Options to split the bill and tip.']],
48
- 'columns': ['Aspect', 'Details']},
49
- 'references': 'https://sundayapp.com/2024-recap-how-sunday-revolutionized-restaurant-payments/, https://sundayapp.com/blog/, https://www.checkout.com/case-studies/sunday-brings-the-ease-of-online-payments-to-the-offline-dining-experience'}
50
-
51
- @dataclass
52
- class Research_paper_test:
53
- test_data:dict
54
-
55
- test_paper=Research_paper_test
56
- test_paper.test_data=test_data
57
-
58
-
59
- # Initialize the agent
60
- agent = Main_agent()
61
-
62
- # Initialize session state
63
- if 'chat_history' not in st.session_state:
64
- st.session_state.chat_history = []
65
-
66
- if 'table_data' not in st.session_state:
67
- st.session_state.table_data = {}
68
- if 'quick_search_results' not in st.session_state:
69
- st.session_state.quick_search_results = []
70
- if 'research_paper' not in st.session_state:
71
- st.session_state.research_paper = {}
72
-
73
- if 'agent_memory' not in st.session_state:
74
- st.session_state.agent_memory = []
75
-
76
- if 'loop' not in st.session_state:
77
- st.session_state.loop = asyncio.new_event_loop()
78
- asyncio.set_event_loop(st.session_state.loop)
79
-
80
- agent.deps.deep_search_results = st.session_state.research_paper
81
- agent.deps.quick_search_results = st.session_state.quick_search_results
82
- agent.deps.table_data = st.session_state.table_data
83
- agent.memory.messages = st.session_state.agent_memory
84
-
85
- def paper_to_markdown(paper: dict) -> str:
86
- """Convert a paper dictionary into a markdown string."""
87
- markdown = []
88
-
89
- # Add title
90
- markdown.append(f"# {paper.get('title')}")
91
- markdown.append("\n\n")
92
- if paper.get('image_url'):
93
- markdown.append(f"![Image]({paper.get('image_url')})\n")
94
- markdown.append("\n\n")
95
-
96
- # Add body sections
97
- for section in paper.get('paragraphs', []):
98
- markdown.append(f"## {section.get('title')}\n")
99
- if section.get('content'):
100
- markdown.append(section.get('content'))
101
- markdown.append("\n")
102
- markdown.append("\n\n")
103
-
104
- if paper.get('table'):
105
- try:
106
- markdown.append(pd.DataFrame(data=paper.get('table')['data'],
107
- columns=paper.get('table')['columns']).to_markdown())
108
- except:
109
- markdown.append(pd.DataFrame(paper.get('table')).to_markdown())
110
- markdown.append("\n\n")
111
-
112
- # Add references
113
- markdown.append("## References\n")
114
- markdown.append(str(paper.get('references')))
115
-
116
- return "".join(markdown)
117
-
118
- def download_as_docx(paper: dict) -> str:
119
- """Convert a paper dictionary into a DOCX file."""
120
- def temp_image_file(url: str):
121
- image = requests.get(url)
122
- image = Image.open(BytesIO(image.content))
123
- with tempfile.NamedTemporaryFile(mode='w', suffix='.png', delete=False) as temp_file:
124
- image.save(temp_file.name)
125
- image_file_path = temp_file.name
126
- return image_file_path
127
- if paper.get('image_url'):
128
- image_path = temp_image_file(paper.get('image_url'))
129
- else:
130
- image_path = None
131
-
132
- # Prepare markdown
133
- markdown = []
134
-
135
- # Add title
136
- markdown.append(f"# {paper.get('title')}")
137
- markdown.append("\n\n")
138
- if image_path:
139
- markdown.append(f"![Image]({image_path})\n")
140
- markdown.append("\n\n")
141
-
142
- # Add body sections
143
- for section in paper.get('paragraphs', []):
144
- markdown.append(f"## {section.get('title')}\n")
145
- if section.get('content'):
146
- markdown.append(section.get('content'))
147
- markdown.append("\n")
148
- markdown.append("\n\n")
149
-
150
- if paper.get('table'):
151
- try:
152
- markdown.append(pd.DataFrame(data=paper.get('table')['data'],
153
- columns=paper.get('table')['columns']).to_markdown())
154
- except:
155
- markdown.append(pd.DataFrame(paper.get('table')).to_markdown())
156
- markdown.append("\n\n")
157
-
158
- # Add references
159
- markdown.append("## References\n")
160
- markdown.append(str(paper.get('references')))
161
-
162
- markdown_str = "".join(markdown)
163
-
164
- # Create a temporary file
165
- with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as temp_file:
166
- temp_file.write(markdown_str)
167
- temp_file_path = temp_file.name
168
-
169
- # Create a new document and load from the temporary files
170
- document = Document()
171
- document.LoadFromFile(temp_file_path)
172
-
173
- # Save as DOCX
174
- output_path = "output.docx"
175
- document.SaveToFile(output_path, FileFormat.Docx)
176
-
177
- # Clean up temporary files
178
- os.unlink(temp_file_path)
179
- if image_path:
180
- os.unlink(image_path)
181
-
182
- return output_path
183
-
184
- async def process_query(query: str):
185
- """Process a user query and update the research paper."""
186
- response = await agent.chat(query)
187
- st.session_state.chat_history.append({"role": "user", "content": query})
188
- st.session_state.chat_history.append({"role": "assistant", "content": str(response)})
189
- st.session_state.agent_memory = agent.memory.messages
190
- # Update research paper if available
191
- if agent.deps.deep_search_results:
192
- st.session_state.research_paper = agent.deps.deep_search_results
193
- st.session_state.table_data = agent.deps.table_data
194
- if agent.deps.table_data:
195
- st.session_state.table_data = agent.deps.table_data
196
- if agent.deps.quick_search_results:
197
- st.session_state.quick_search_results = agent.deps.quick_search_results
198
-
199
-
200
- def process_query_sync(query: str):
201
- """Synchronous wrapper for async process_query"""
202
- if not st.session_state.loop.is_running():
203
- return st.session_state.loop.run_until_complete(process_query(query))
204
- else:
205
- # Create a new event loop if the current one is running
206
- loop = asyncio.new_event_loop()
207
- asyncio.set_event_loop(loop)
208
- try:
209
- return loop.run_until_complete(process_query(query))
210
- finally:
211
- loop.close()
212
-
213
- def reset_chat():
214
- """Reset the chat history and agent state."""
215
- agent.reset()
216
- st.session_state.chat_history = []
217
- st.session_state.research_paper = {}
218
- st.session_state.table_data = {}
219
- st.session_state.quick_search_results = []
220
- st.session_state.agent_memory = []
221
-
222
-
223
-
224
- # Streamlit UI
225
- st.title("Research Assistant Chatbot")
226
-
227
- # Create a container for the chat interface
228
- chat_container = st.container()
229
-
230
- # Create two columns - one for chat and one for controls
231
-
232
-
233
-
234
- # Chat interface with custom styling
235
- st.markdown("""
236
- <style>
237
- .stChatMessage {
238
- padding: 20px;
239
- border-radius: 10px;
240
- margin-bottom: 10px;
241
- }
242
- .user-message {
243
- background-color: #e6f3ff;
244
- text-align: right;
245
- }
246
- .assistant-message {
247
- background-color: #f0f0f0;
248
- text-align: left;
249
- }
250
- </style>
251
- """, unsafe_allow_html=True)
252
-
253
- # Chat messages in a scrollable container
254
- with st.container(height=300):
255
- for message in st.session_state.chat_history:
256
- with st.chat_message(message["role"], avatar="🧑" if message["role"] == "user" else "🤖"):
257
- st.write(message["content"])
258
-
259
- # Input area at the bottom
260
- with st.container():
261
- query = st.text_input("Ask me anything...", key="query_input", placeholder="Type your question here...")
262
- col3, col4 = st.columns([6, 1])
263
- with col3:
264
- if st.button("Submit", use_container_width=True):
265
- if query:
266
- with st.spinner('Processing your request...'):
267
- process_query_sync(query)
268
- st.rerun()
269
-
270
-
271
- # Control buttons in the sidebar
272
- with st.sidebar:
273
- st.markdown("### Helpful Tips")
274
- st.markdown("---")
275
- st.markdown("""reset chat if you want to start over or if the agent is not responding properly""")
276
- if st.button("Reset Chat", use_container_width=True):
277
- reset_chat()
278
-
279
- # Add some helpful tips
280
- st.markdown("---")
281
- st.markdown("### Tips")
282
- st.markdown("""
283
- - ask the agent about its capabilities and what it can do
284
- - the table is editable, you can edit in the files section or in the chat
285
- - the research paper is also editable, you can edit in the chat by asking the agent to edit the research paper
286
- - the agent can also add a table to the research paper, you can see the table in the files section or in the chat
287
- """)
288
-
289
- st.markdown('### Files ')
290
-
291
- # Research Paper popover
292
-
293
- if st.session_state.research_paper :
294
- with st.popover("📄 Research Paper",use_container_width=True):
295
- st.markdown("""
296
- <style>
297
- .paper-preview {
298
- border: 1px solid #e0e0e0;
299
- border-radius: 5px;
300
- padding: 10px;
301
- margin-bottom: 10px;
302
- }
303
- </style>
304
- """, unsafe_allow_html=True)
305
-
306
- # Paper content
307
- st.markdown(paper_to_markdown(st.session_state.research_paper))
308
-
309
- # Download button
310
- if st.button("📥 Save as DOCX", use_container_width=True):
311
- with st.spinner('Preparing document...'):
312
- output_path = download_as_docx(st.session_state.research_paper)
313
- with open(output_path, "rb") as file:
314
- st.download_button(
315
- label="Download",
316
- data=file,
317
- file_name="research_paper.docx",
318
- mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
319
- )
320
- os.unlink(output_path)
321
-
322
- # Table popover
323
- if st.session_state.table_data:
324
- with st.popover("📊 Editable Table",use_container_width=True):
325
- try:
326
- try:
327
- df = pd.DataFrame(data=st.session_state.table_data['data'],
328
- columns=st.session_state.table_data['columns'])
329
- except:
330
- df = pd.DataFrame(st.session_state.table_data)
331
-
332
-
333
- edited_df = st.data_editor(df)
334
- if st.session_state.research_paper:
335
- if st.button("💾 add table to research paper", use_container_width=True):
336
- # Convert DataFrame back to the correct structure
337
- table_dict = {
338
- 'data': edited_df.values.tolist(),
339
- 'columns': edited_df.columns.tolist()
340
- }
341
- st.session_state.research_paper['table'] = table_dict
342
- st.session_state.table_data = table_dict
343
- st.success("Table updated successfully!")
344
- st.rerun()
345
- except Exception as e:
346
- st.error(f"Error loading table data: {str(e)}")
347
-
348
-