Mattral commited on
Commit
dbf67ec
·
verified ·
1 Parent(s): 7422d55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -88
app.py CHANGED
@@ -13,11 +13,7 @@ logging.basicConfig(level=logging.INFO)
13
  logger = logging.getLogger(__name__)
14
 
15
  # Page configuration
16
- st.set_page_config(
17
- page_title="DeepSeek Chatbot - ruslanmv.com",
18
- page_icon="🤖",
19
- layout="centered"
20
- )
21
 
22
  # Initialize session state for chat history
23
  if "messages" not in st.session_state:
@@ -29,31 +25,13 @@ with st.sidebar:
29
  st.markdown("[Get HuggingFace Token](https://huggingface.co/settings/tokens)")
30
 
31
  # Dropdown to select model
32
- model_options = [
33
- "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
34
- ]
35
  selected_model = st.selectbox("Select Model", model_options, index=0)
36
 
37
- system_message = st.text_area(
38
- "System Message",
39
- value="You are a friendly chatbot created by who Provide clear, accurate, and brief answers. Keep responses polite, engaging, and to the point. If unsure, politely suggest alternatives.",
40
- height=100
41
- )
42
-
43
- max_tokens = st.slider(
44
- "Max Tokens",
45
- 10, 4000, 100
46
- )
47
-
48
- temperature = st.slider(
49
- "Temperature",
50
- 0.1, 4.0, 0.3
51
- )
52
-
53
- top_p = st.slider(
54
- "Top-p",
55
- 0.1, 1.0, 0.6
56
- )
57
 
58
  # Function to query the Hugging Face API
59
  def query(payload, api_url):
@@ -79,11 +57,7 @@ def process_pdf(uploaded_file):
79
  documents = loader.load()
80
 
81
  # Split the documents into chunks
82
- text_splitter = RecursiveCharacterTextSplitter(
83
- chunk_size=1000,
84
- chunk_overlap=200,
85
- add_start_index=True
86
- )
87
  return text_splitter.split_documents(documents)
88
 
89
  # Function to generate response using LangChain
@@ -120,8 +94,13 @@ if uploaded_file:
120
  documents = process_pdf(uploaded_file)
121
  context = "\n\n".join([doc.page_content for doc in documents])
122
 
123
- # Ask the user a question
124
- if prompt := st.chat_input("Type your message..."):
 
 
 
 
 
125
  st.session_state.messages.append({"role": "user", "content": prompt})
126
 
127
  with st.chat_message("user"):
@@ -129,60 +108,14 @@ if uploaded_file:
129
 
130
  try:
131
  with st.spinner("Generating response..."):
132
- # Combine system message and user input into a single prompt
133
- full_prompt = f"{system_message}\n\nUser: {prompt}\nAssistant:"
134
- payload = {
135
- "inputs": full_prompt,
136
- "parameters": {
137
- "max_new_tokens": max_tokens,
138
- "temperature": temperature,
139
- "top_p": top_p,
140
- "return_full_text": False
141
- }
142
- }
143
-
144
- # Dynamically construct the API URL based on the selected model
145
- api_url = f"https://api-inference.huggingface.co/models/{selected_model}"
146
- logger.info(f"Selected model: {selected_model}, API URL: {api_url}")
147
-
148
- # Query the Hugging Face API using the selected model
149
- output = query(payload, api_url)
150
-
151
- # Handle API response
152
- if output is not None and isinstance(output, list) and len(output) > 0:
153
- if 'generated_text' in output[0]:
154
- assistant_response = output[0]['generated_text'].strip()
155
-
156
- # Check for and remove duplicate responses
157
- responses = assistant_response.split("\n</think>\n")
158
- unique_response = responses[0].strip()
159
-
160
- logger.info(f"Generated response: {unique_response}")
161
-
162
- # Append response to chat only once
163
- with st.chat_message("assistant"):
164
- st.markdown(unique_response)
165
-
166
- st.session_state.messages.append({"role": "assistant", "content": unique_response})
167
- else:
168
- logger.error(f"Unexpected API response structure: {output}")
169
- st.error("Error: Unexpected response from the model. Please try again.")
170
- else:
171
- logger.error(f"Empty or invalid API response: {output}")
172
- st.error("Error: Unable to generate a response. Please check the model and try again.")
173
 
174
  except Exception as e:
175
  logger.error(f"Application Error: {str(e)}", exc_info=True)
176
  st.error(f"Application Error: {str(e)}")
177
-
178
- # Allow user to ask a question based on extracted PDF content
179
- if uploaded_file and documents: # Ensure documents exist before proceeding
180
- if prompt := st.chat_input("Ask a question about the PDF content"):
181
- context = "\n\n".join([doc.page_content for doc in documents]) # Get context from documents
182
- answer = generate_response_with_langchain(prompt, context)
183
-
184
- # Show the answer from LangChain model
185
- with st.chat_message("assistant"):
186
- st.markdown(answer)
187
-
188
- st.session_state.messages.append({"role": "assistant", "content": answer})
 
13
  logger = logging.getLogger(__name__)
14
 
15
  # Page configuration
16
+ st.set_page_config(page_title="DeepSeek Chatbot - ruslanmv.com", page_icon="🤖", layout="centered")
 
 
 
 
17
 
18
  # Initialize session state for chat history
19
  if "messages" not in st.session_state:
 
25
  st.markdown("[Get HuggingFace Token](https://huggingface.co/settings/tokens)")
26
 
27
  # Dropdown to select model
28
+ model_options = ["deepseek-ai/DeepSeek-R1-Distill-Qwen-32B"]
 
 
29
  selected_model = st.selectbox("Select Model", model_options, index=0)
30
 
31
+ system_message = st.text_area("System Message", value="You are a friendly chatbot. Provide clear, accurate, and brief answers.", height=100)
32
+ max_tokens = st.slider("Max Tokens", 10, 4000, 100)
33
+ temperature = st.slider("Temperature", 0.1, 4.0, 0.3)
34
+ top_p = st.slider("Top-p", 0.1, 1.0, 0.6)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  # Function to query the Hugging Face API
37
  def query(payload, api_url):
 
57
  documents = loader.load()
58
 
59
  # Split the documents into chunks
60
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200, add_start_index=True)
 
 
 
 
61
  return text_splitter.split_documents(documents)
62
 
63
  # Function to generate response using LangChain
 
94
  documents = process_pdf(uploaded_file)
95
  context = "\n\n".join([doc.page_content for doc in documents])
96
 
97
+ # Combine system message and user input into a single prompt
98
+ prompt_input = "Ask a question about the PDF content"
99
+
100
+ # Show the PDF-based question input if the PDF is uploaded
101
+ prompt = st.chat_input(prompt_input) if documents else None
102
+
103
+ if prompt:
104
  st.session_state.messages.append({"role": "user", "content": prompt})
105
 
106
  with st.chat_message("user"):
 
108
 
109
  try:
110
  with st.spinner("Generating response..."):
111
+ answer = generate_response_with_langchain(prompt, context)
112
+
113
+ # Show the answer from LangChain model
114
+ with st.chat_message("assistant"):
115
+ st.markdown(answer)
116
+
117
+ st.session_state.messages.append({"role": "assistant", "content": answer})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  except Exception as e:
120
  logger.error(f"Application Error: {str(e)}", exc_info=True)
121
  st.error(f"Application Error: {str(e)}")