Spaces:
Sleeping
Sleeping
overly restricted error
Browse files
app.py
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
import os
|
2 |
import logging
|
3 |
import re
|
4 |
-
from langchain_community.vectorstores import Chroma
|
5 |
from langchain_huggingface import HuggingFaceEmbeddings
|
6 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
7 |
from langchain_groq import ChatGroq
|
@@ -61,67 +61,22 @@ def load_documents(file_paths):
|
|
61 |
logger.error(f"Error processing file {file_path}: {e}")
|
62 |
return docs
|
63 |
|
64 |
-
|
65 |
-
sentences = re.findall(r'[^.!?]*[.!?]', text)
|
66 |
-
if sentences:
|
67 |
-
return ' '.join(s.strip() for s in sentences)
|
68 |
-
return text
|
69 |
|
70 |
-
# --- Added: Handling "Not Feasible" Keywords and Gibberish Inputs ---
|
71 |
def is_valid_input(text):
|
72 |
-
"""
|
73 |
-
Validate the user's input question.
|
74 |
-
Returns a tuple (is_valid, message).
|
75 |
-
"""
|
76 |
if not text or text.strip() == "":
|
77 |
return False, "Input cannot be empty. Please provide a meaningful question."
|
78 |
-
|
79 |
-
if not re.search('[A-Za-z]', text):
|
80 |
-
return False, "Input must contain alphabetic characters."
|
81 |
-
|
82 |
if len(text.strip()) < 5:
|
83 |
return False, "Input is too short. Please provide a more detailed question."
|
84 |
-
|
85 |
-
#
|
86 |
-
not_feasible_keywords = [
|
87 |
-
"illegal", "harmful", "dangerous", "unethical", "inappropriate",
|
88 |
-
"forbidden", "restricted", "banned", "prohibited", "secret"
|
89 |
-
]
|
90 |
-
|
91 |
-
# Check for not feasible keywords (case-insensitive)
|
92 |
-
pattern = re.compile(r'\b(' + '|'.join(not_feasible_keywords) + r')\b', re.IGNORECASE)
|
93 |
-
if pattern.search(text):
|
94 |
-
return False, "Your question contains restricted or inappropriate content. Please modify your query."
|
95 |
-
|
96 |
-
# --- Added: Gibberish Detection ---
|
97 |
-
# Simple heuristic: Check the ratio of alphabetic characters to total characters
|
98 |
-
total_chars = len(text)
|
99 |
-
alpha_chars = len(re.findall(r'[A-Za-z]', text))
|
100 |
-
ratio = alpha_chars / total_chars if total_chars > 0 else 0
|
101 |
-
|
102 |
-
if ratio < 0.6:
|
103 |
-
return False, "Your input appears to be gibberish or nonsensical. Please enter a clear and meaningful question."
|
104 |
-
|
105 |
-
# Additionally, check for a minimum number of recognizable words
|
106 |
words = re.findall(r'\b\w+\b', text)
|
107 |
-
|
108 |
-
|
109 |
-
if len(recognized_words) < max(3, len(words) * 0.4):
|
110 |
-
return False, "Your input contains too many unrecognizable words. Please enter a clear and meaningful question."
|
111 |
-
|
112 |
-
return True, "Valid input."
|
113 |
|
114 |
-
|
115 |
-
# In a production environment, consider using a more comprehensive dictionary or language model
|
116 |
-
recognized_words_set = set([
|
117 |
-
'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'I',
|
118 |
-
'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at',
|
119 |
-
'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her',
|
120 |
-
'she', 'or', 'an', 'will', 'my', 'one', 'all', 'would', 'there',
|
121 |
-
'their', 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get',
|
122 |
-
'which', 'go', 'me'
|
123 |
-
# Add more words as needed
|
124 |
-
])
|
125 |
|
126 |
def initialize_llm(model, temperature, max_tokens):
|
127 |
prompt_allocation = int(max_tokens * 0.2)
|
@@ -152,20 +107,13 @@ def create_rag_pipeline(file_paths, model, temperature, max_tokens):
|
|
152 |
embedding=embedding_model,
|
153 |
persist_directory="/tmp/chroma_db"
|
154 |
)
|
155 |
-
# vectorstore.persist() # Deprecated in Chroma 0.4.x
|
156 |
|
157 |
retriever = vectorstore.as_retriever()
|
158 |
|
159 |
-
# --- Improved Prompt Template ---
|
160 |
custom_prompt_template = PromptTemplate(
|
161 |
input_variables=["context", "question"],
|
162 |
template="""
|
163 |
You are an AI assistant specialized in daily wellness. Provide a concise, thorough, and stand-alone answer to the user's question based on the given context. Include relevant examples or schedules where beneficial. **When listing steps or guidelines, format them as a numbered list with appropriate markdown formatting.** The final answer should be coherent, self-contained, and end with a complete sentence.
|
164 |
-
|
165 |
-
If the question contains restricted or inappropriate content, respond with a polite message indicating that you cannot assist with that request.
|
166 |
-
|
167 |
-
If the question appears to be gibberish or nonsensical, respond with a polite message requesting clarification or a more coherent question.
|
168 |
-
|
169 |
Context:
|
170 |
{context}
|
171 |
Question:
|
@@ -196,10 +144,7 @@ def answer_question(model, temperature, max_tokens, question):
|
|
196 |
return "The system is currently unavailable. Please try again later."
|
197 |
try:
|
198 |
answer = rag_chain.run(question)
|
199 |
-
|
200 |
-
# complete_answer = ensure_complete_sentences(answer)
|
201 |
-
complete_answer = answer
|
202 |
-
return complete_answer
|
203 |
except Exception as e_inner:
|
204 |
logger.error(f"Error: {e_inner}")
|
205 |
return "An error occurred while processing your request."
|
@@ -215,7 +160,7 @@ interface = gr.Interface(
|
|
215 |
gr.Slider(label="Max Tokens", minimum=200, maximum=2048, step=1, value=max_tokens),
|
216 |
gr.Textbox(label="Question", placeholder="e.g., What is box breathing and how does it help reduce anxiety?")
|
217 |
],
|
218 |
-
outputs=gr.Markdown(label="Answer"),
|
219 |
title="Daily Wellness AI",
|
220 |
description="Ask questions about daily wellness and receive a concise, complete answer.",
|
221 |
examples=[
|
|
|
1 |
import os
|
2 |
import logging
|
3 |
import re
|
4 |
+
from langchain_community.vectorstores import Chroma
|
5 |
from langchain_huggingface import HuggingFaceEmbeddings
|
6 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
7 |
from langchain_groq import ChatGroq
|
|
|
61 |
logger.error(f"Error processing file {file_path}: {e}")
|
62 |
return docs
|
63 |
|
64 |
+
# Simplify input validation
|
|
|
|
|
|
|
|
|
65 |
|
|
|
66 |
def is_valid_input(text):
|
67 |
+
"""Validate the user's input question."""
|
|
|
|
|
|
|
68 |
if not text or text.strip() == "":
|
69 |
return False, "Input cannot be empty. Please provide a meaningful question."
|
70 |
+
|
|
|
|
|
|
|
71 |
if len(text.strip()) < 5:
|
72 |
return False, "Input is too short. Please provide a more detailed question."
|
73 |
+
|
74 |
+
# Gibberish detection: Ensure text contains valid words
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
words = re.findall(r'\b\w+\b', text)
|
76 |
+
if len(words) < 3: # Require at least three recognizable words
|
77 |
+
return False, "Input appears incomplete. Please provide a more meaningful question."
|
|
|
|
|
|
|
|
|
78 |
|
79 |
+
return True, "Valid input."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
|
81 |
def initialize_llm(model, temperature, max_tokens):
|
82 |
prompt_allocation = int(max_tokens * 0.2)
|
|
|
107 |
embedding=embedding_model,
|
108 |
persist_directory="/tmp/chroma_db"
|
109 |
)
|
|
|
110 |
|
111 |
retriever = vectorstore.as_retriever()
|
112 |
|
|
|
113 |
custom_prompt_template = PromptTemplate(
|
114 |
input_variables=["context", "question"],
|
115 |
template="""
|
116 |
You are an AI assistant specialized in daily wellness. Provide a concise, thorough, and stand-alone answer to the user's question based on the given context. Include relevant examples or schedules where beneficial. **When listing steps or guidelines, format them as a numbered list with appropriate markdown formatting.** The final answer should be coherent, self-contained, and end with a complete sentence.
|
|
|
|
|
|
|
|
|
|
|
117 |
Context:
|
118 |
{context}
|
119 |
Question:
|
|
|
144 |
return "The system is currently unavailable. Please try again later."
|
145 |
try:
|
146 |
answer = rag_chain.run(question)
|
147 |
+
return answer.strip()
|
|
|
|
|
|
|
148 |
except Exception as e_inner:
|
149 |
logger.error(f"Error: {e_inner}")
|
150 |
return "An error occurred while processing your request."
|
|
|
160 |
gr.Slider(label="Max Tokens", minimum=200, maximum=2048, step=1, value=max_tokens),
|
161 |
gr.Textbox(label="Question", placeholder="e.g., What is box breathing and how does it help reduce anxiety?")
|
162 |
],
|
163 |
+
outputs=gr.Markdown(label="Answer"),
|
164 |
title="Daily Wellness AI",
|
165 |
description="Ask questions about daily wellness and receive a concise, complete answer.",
|
166 |
examples=[
|