Copain22 commited on
Commit
7a0e378
·
verified ·
1 Parent(s): 7d8a35f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -103
app.py CHANGED
@@ -9,111 +9,93 @@ from langchain.memory import ConversationBufferMemory
9
  from langchain.text_splitter import RecursiveCharacterTextSplitter
10
  from langchain_community.document_loaders import PyMuPDFLoader
11
 
12
- # App config
13
- st.set_page_config(page_title="Café Eleven", page_icon="☕")
14
- st.title("Café Eleven Ordering Assistant")
 
15
 
16
- # Initialize chat
17
- if "messages" not in st.session_state:
18
- st.session_state.messages = [{
19
- "role": "assistant",
20
- "content": "Hi! Welcome to Café Eleven. What would you like to order today?"
21
- }]
22
 
23
- # Display messages
24
- for msg in st.session_state.messages:
25
- st.chat_message(msg["role"]).write(msg["content"])
26
 
27
- # Chat functions
28
- @st.cache_resource
29
- def load_chain():
30
- # Load all PDFs in directory
31
- pdf_files = [str(p) for p in Path(".").glob("*.pdf")]
32
- if not pdf_files:
33
- st.error("No PDF files found! Please upload menu PDFs.")
34
- st.stop()
35
-
36
- # Load and split documents
37
- docs = []
38
- for pdf in pdf_files:
39
- loader = PyMuPDFLoader(pdf)
40
- docs.extend(loader.load())
41
-
42
- text_splitter = RecursiveCharacterTextSplitter(
43
- chunk_size=1000,
44
- chunk_overlap=200
45
- )
46
- splits = text_splitter.split_documents(docs)
47
-
48
- # Setup vectorstore
49
- embeddings = HuggingFaceEmbeddings(
50
- model_name="sentence-transformers/all-mpnet-base-v2"
51
- )
52
- vectorstore = FAISS.from_documents(splits, embeddings)
53
-
54
- # Setup LLM
55
- llm = HuggingFaceHub(
56
- repo_id="meta-llama/Llama-2-7b-chat-hf",
57
- huggingfacehub_api_token=os.environ["HF_TOKEN"],
58
- model_kwargs={
59
- "temperature": 0.2,
60
- "max_length": 256
61
- }
62
- )
63
-
64
- # Create chain with system prompt
65
- return ConversationalRetrievalChain.from_llm(
66
- llm=llm,
67
- retriever=vectorstore.as_retriever(),
68
- memory=ConversationBufferMemory(
69
- memory_key="chat_history",
70
- return_messages=True
71
- ),
72
- condense_question_prompt="""
73
- You are a friendly café assistant. Your job is to:
74
- 1. Greet customers warmly
75
- 2. Help them place orders
76
- 3. Suggest menu items
77
- 4. Never make up items not in the menu
78
- Current conversation:
79
- {chat_history}
80
- Question: {question}
81
- """
82
- )
83
 
84
- # Chat input
85
- if prompt := st.chat_input("Your order..."):
86
- st.session_state.messages.append({"role": "user", "content": prompt})
87
- st.chat_message("user").write(prompt)
88
-
89
- with st.spinner("Preparing your order..."):
90
- try:
91
- chain = load_chain()
92
- response = chain({"question": prompt})["answer"]
93
-
94
- # Format response cleanly
95
- if "menu" in prompt.lower():
96
- response = "Here are our offerings:\n" + response
97
- elif "thank" in prompt.lower():
98
- response = "You're welcome! " + response
99
-
100
- st.session_state.messages.append({"role": "assistant", "content": response})
101
- st.chat_message("assistant").write(response)
102
-
103
- except Exception as e:
104
- st.error(f"Sorry, something went wrong: {str(e)}")
105
 
106
- # PDF upload section
107
- with st.sidebar:
108
- st.subheader("Menu Management")
109
- uploaded_files = st.file_uploader(
110
- "Upload PDF menus",
111
- type="pdf",
112
- accept_multiple_files=True
113
- )
114
- if uploaded_files:
115
- for file in uploaded_files:
116
- with open(file.name, "wb") as f:
117
- f.write(file.getbuffer())
118
- st.success(f"Uploaded {len(uploaded_files)} menu(s)")
119
- st.cache_resource.clear() # Refresh the vectorstore
 
 
 
 
 
9
  from langchain.text_splitter import RecursiveCharacterTextSplitter
10
  from langchain_community.document_loaders import PyMuPDFLoader
11
 
12
+ def main():
13
+ # App config
14
+ st.set_page_config(page_title="Café Eleven", page_icon="☕")
15
+ st.title("☕ Café Eleven Ordering Assistant")
16
 
17
+ # Initialize chat (must be inside main())
18
+ if "messages" not in st.session_state:
19
+ st.session_state.messages = [{
20
+ "role": "assistant",
21
+ "content": "Hi! Welcome to Café Eleven. What would you like to order today?"
22
+ }]
23
 
24
+ # Display messages
25
+ for msg in st.session_state.messages:
26
+ st.chat_message(msg["role"]).write(msg["content"])
27
 
28
+ # Chat functions
29
+ @st.cache_resource
30
+ def load_chain():
31
+ pdf_files = [str(p) for p in Path(".").glob("*.pdf")]
32
+ if not pdf_files:
33
+ st.error("No PDF files found! Please upload menu PDFs.")
34
+ st.stop()
35
+
36
+ docs = []
37
+ for pdf in pdf_files:
38
+ loader = PyMuPDFLoader(pdf)
39
+ docs.extend(loader.load())
40
+
41
+ text_splitter = RecursiveCharacterTextSplitter(
42
+ chunk_size=1000,
43
+ chunk_overlap=200
44
+ )
45
+ splits = text_splitter.split_documents(docs)
46
+
47
+ embeddings = HuggingFaceEmbeddings(
48
+ model_name="sentence-transformers/all-mpnet-base-v2"
49
+ )
50
+ vectorstore = FAISS.from_documents(splits, embeddings)
51
+
52
+ llm = HuggingFaceHub(
53
+ repo_id="meta-llama/Llama-2-7b-chat-hf",
54
+ huggingfacehub_api_token=os.environ["HF_TOKEN"],
55
+ model_kwargs={
56
+ "temperature": 0.2,
57
+ "max_length": 256
58
+ }
59
+ )
60
+
61
+ return ConversationalRetrievalChain.from_llm(
62
+ llm=llm,
63
+ retriever=vectorstore.as_retriever(),
64
+ memory=ConversationBufferMemory(
65
+ memory_key="chat_history",
66
+ return_messages=True
67
+ )
68
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ # Chat input
71
+ if prompt := st.chat_input("Your order..."):
72
+ st.session_state.messages.append({"role": "user", "content": prompt})
73
+ st.chat_message("user").write(prompt)
74
+
75
+ with st.spinner("Preparing your order..."):
76
+ try:
77
+ chain = load_chain()
78
+ response = chain({"question": prompt})["answer"]
79
+ st.session_state.messages.append({"role": "assistant", "content": response})
80
+ st.chat_message("assistant").write(response)
81
+ except Exception as e:
82
+ st.error(f"Sorry, something went wrong: {str(e)}")
 
 
 
 
 
 
 
 
83
 
84
+ # PDF upload
85
+ with st.sidebar:
86
+ st.subheader("Menu Management")
87
+ uploaded_files = st.file_uploader(
88
+ "Upload PDF menus",
89
+ type="pdf",
90
+ accept_multiple_files=True
91
+ )
92
+ if uploaded_files:
93
+ for file in uploaded_files:
94
+ with open(file.name, "wb") as f:
95
+ f.write(file.getbuffer())
96
+ st.success(f"Uploaded {len(uploaded_files)} menu(s)")
97
+ st.cache_resource.clear()
98
+
99
+ # Required for Hugging Face Spaces
100
+ if __name__ == "__main__":
101
+ main()