Spaces:
Build error
Build error
Test push3
Browse files
app.py
CHANGED
|
@@ -1,113 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
""
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
):
|
| 18 |
messages = [{"role": "system", "content": system_message}]
|
| 19 |
-
|
| 20 |
-
for
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
messages.append({"role": "user", "content": message})
|
| 27 |
|
| 28 |
response = ""
|
| 29 |
-
|
| 30 |
-
for message in client.chat_completion(
|
| 31 |
messages,
|
| 32 |
max_tokens=max_tokens,
|
| 33 |
stream=True,
|
| 34 |
temperature=temperature,
|
| 35 |
top_p=top_p,
|
| 36 |
):
|
| 37 |
-
token =
|
| 38 |
-
|
| 39 |
response += token
|
| 40 |
yield response
|
| 41 |
|
| 42 |
-
|
| 43 |
-
"""
|
| 44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
| 45 |
-
"""
|
| 46 |
-
demo = gr.ChatInterface(
|
| 47 |
-
respond,
|
| 48 |
-
additional_inputs=[
|
| 49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 52 |
-
gr.Slider(
|
| 53 |
-
minimum=0.1,
|
| 54 |
-
maximum=1.0,
|
| 55 |
-
value=0.95,
|
| 56 |
-
step=0.05,
|
| 57 |
-
label="Top-p (nucleus sampling)",
|
| 58 |
-
),
|
| 59 |
-
],
|
| 60 |
-
)
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
# Install required packages
|
| 64 |
-
# pip install langchain huggingface_hub pandas faiss-cpu numpy transformers torch accelerate bitsandbytes gradio
|
| 65 |
-
|
| 66 |
-
import pandas as pd
|
| 67 |
-
import numpy as np
|
| 68 |
-
from langchain.vectorstores import FAISS
|
| 69 |
-
from langchain.embeddings import HuggingFaceEmbeddings
|
| 70 |
-
from langchain.chains import RetrievalQA
|
| 71 |
-
from langchain.prompts import PromptTemplate
|
| 72 |
-
from langchain.llms import HuggingFacePipeline
|
| 73 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 74 |
-
import torch
|
| 75 |
-
import gradio as gr
|
| 76 |
-
|
| 77 |
def load_embeddings(csv_path):
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
x.strip("[]").replace("\n", ""),
|
| 87 |
-
sep=", ",
|
| 88 |
-
dtype=np.float32
|
| 89 |
-
)
|
| 90 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
return df['Cleaned_Ideas'].tolist(), np.array(df['Embeddings'].tolist())
|
| 99 |
-
|
| 100 |
-
except Exception as e:
|
| 101 |
-
print(f"Error loading embeddings: {str(e)}")
|
| 102 |
-
raise
|
| 103 |
-
|
| 104 |
-
# 1. Load texts and embeddings from CSV
|
| 105 |
-
texts, embeddings = load_embeddings("ideas_with_embeddings.csv")
|
| 106 |
-
|
| 107 |
-
# 2. Improved embedding model and FAISS configuration
|
| 108 |
-
try:
|
| 109 |
embedding_model = HuggingFaceEmbeddings(
|
| 110 |
-
model_name=
|
| 111 |
model_kwargs={'device': 'cpu'},
|
| 112 |
encode_kwargs={'normalize_embeddings': True}
|
| 113 |
)
|
|
@@ -117,152 +89,122 @@ try:
|
|
| 117 |
embedding=embedding_model,
|
| 118 |
normalize_L2=True
|
| 119 |
)
|
| 120 |
-
print(f"FAISS index created with {vector_store.index.ntotal} entries")
|
| 121 |
-
|
| 122 |
-
except Exception as e:
|
| 123 |
-
print(f"Vector store creation failed: {str(e)}")
|
| 124 |
-
raise
|
| 125 |
|
| 126 |
-
#
|
| 127 |
-
|
| 128 |
-
try:
|
| 129 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 130 |
model = AutoModelForCausalLM.from_pretrained(
|
| 131 |
-
|
| 132 |
device_map="auto",
|
| 133 |
torch_dtype=torch.float16,
|
| 134 |
trust_remote_code=True
|
| 135 |
)
|
| 136 |
-
print("GPT-Neo 1.3B model loaded successfully.")
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
top_p=0.9,
|
| 151 |
-
repetition_penalty=1.1,
|
| 152 |
-
do_sample=True,
|
| 153 |
-
return_full_text=False,
|
| 154 |
-
pad_token_id=tokenizer.eos_token_id
|
| 155 |
-
)
|
| 156 |
-
|
| 157 |
-
llm = HuggingFacePipeline(pipeline=pipe)
|
| 158 |
-
|
| 159 |
-
# 4. Enhanced prompt template
|
| 160 |
-
template = """<context>
|
| 161 |
-
{context}
|
| 162 |
-
</context>
|
| 163 |
-
|
| 164 |
-
<question>
|
| 165 |
-
{question}
|
| 166 |
-
</question>
|
| 167 |
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
|
| 173 |
-
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
-
|
| 178 |
-
template=template,
|
| 179 |
-
input_variables=["context", "question"],
|
| 180 |
-
template_format="f-string"
|
| 181 |
-
)
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
|
|
|
|
|
|
| 205 |
|
| 206 |
-
#
|
| 207 |
-
def
|
| 208 |
-
|
| 209 |
-
return "Please enter a valid question", ""
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
with gr.Blocks(title="Philosophical Concepts RAG v2") as demo:
|
| 229 |
-
gr.Markdown("# Enhanced Philosophical RAG System")
|
| 230 |
-
gr.Markdown("Yay Now with improved context understanding and source verification")
|
| 231 |
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
)
|
| 239 |
-
|
|
|
|
| 240 |
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
[
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
],
|
| 260 |
-
inputs=query_input
|
| 261 |
-
)
|
| 262 |
-
|
| 263 |
return demo
|
| 264 |
|
| 265 |
-
# 8. Launch the interface
|
| 266 |
if __name__ == "__main__":
|
| 267 |
-
demo =
|
| 268 |
-
demo.launch(share=True)
|
|
|
|
| 1 |
+
# Install required packages first:
|
| 2 |
+
# pip install langchain huggingface_hub pandas faiss-cpu numpy transformers torch accelerate bitsandbytes gradio
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
import gradio as gr
|
| 7 |
+
import torch
|
| 8 |
+
from langchain.vectorstores import FAISS
|
| 9 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 10 |
+
from langchain.chains import RetrievalQA
|
| 11 |
+
from langchain.prompts import PromptTemplate
|
| 12 |
+
from langchain.llms import HuggingFacePipeline
|
| 13 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 14 |
from huggingface_hub import InferenceClient
|
| 15 |
|
| 16 |
+
# Configuration for both components
|
| 17 |
+
EMBEDDING_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
|
| 18 |
+
LLM_MODEL_NAME = "EleutherAI/gpt-neo-1.3B"
|
| 19 |
+
CHAT_MODEL_NAME = "HuggingFaceH4/zephyr-7b-beta"
|
| 20 |
+
|
| 21 |
+
# ------ Chat Component ------
|
| 22 |
+
chat_client = InferenceClient(CHAT_MODEL_NAME)
|
| 23 |
+
|
| 24 |
+
def chat_respond(
|
| 25 |
+
message: str,
|
| 26 |
+
history: list[list[str]],
|
| 27 |
+
system_message: str,
|
| 28 |
+
max_tokens: int,
|
| 29 |
+
temperature: float,
|
| 30 |
+
top_p: float,
|
| 31 |
):
|
| 32 |
messages = [{"role": "system", "content": system_message}]
|
| 33 |
+
|
| 34 |
+
for human, assistant in history:
|
| 35 |
+
messages.extend([
|
| 36 |
+
{"role": "user", "content": human},
|
| 37 |
+
{"role": "assistant", "content": assistant}
|
| 38 |
+
])
|
| 39 |
+
|
| 40 |
messages.append({"role": "user", "content": message})
|
| 41 |
|
| 42 |
response = ""
|
| 43 |
+
for chunk in chat_client.chat_completion(
|
|
|
|
| 44 |
messages,
|
| 45 |
max_tokens=max_tokens,
|
| 46 |
stream=True,
|
| 47 |
temperature=temperature,
|
| 48 |
top_p=top_p,
|
| 49 |
):
|
| 50 |
+
token = chunk.choices[0].delta.content
|
|
|
|
| 51 |
response += token
|
| 52 |
yield response
|
| 53 |
|
| 54 |
+
# ------ RAG Component ------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
def load_embeddings(csv_path):
|
| 56 |
+
df = pd.read_csv(csv_path)
|
| 57 |
+
|
| 58 |
+
if 'Cleaned_Ideas' not in df.columns or 'Embeddings' not in df.columns:
|
| 59 |
+
raise ValueError("CSV must contain 'Cleaned_Ideas' and 'Embeddings' columns")
|
| 60 |
|
| 61 |
+
df['Embeddings'] = df['Embeddings'].apply(
|
| 62 |
+
lambda x: np.fromstring(
|
| 63 |
+
x.strip("[]").replace("\n", ""),
|
| 64 |
+
sep=", ",
|
| 65 |
+
dtype=np.float32
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
)
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
expected_dim = 768
|
| 70 |
+
valid_embeddings = df['Embeddings'].apply(lambda x: len(x) == expected_dim)
|
| 71 |
+
if not valid_embeddings.all():
|
| 72 |
+
invalid_count = len(df) - valid_embeddings.sum()
|
| 73 |
+
raise ValueError(f"{invalid_count} entries have invalid embedding dimensions")
|
| 74 |
|
| 75 |
+
return df['Cleaned_Ideas'].tolist(), np.array(df['Embeddings'].tolist())
|
| 76 |
+
# Fixed here → ↑
|
| 77 |
+
def setup_rag_system():
|
| 78 |
+
# Load data and create vector store
|
| 79 |
+
texts, embeddings = load_embeddings("ideas_with_embeddings.csv")
|
| 80 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
embedding_model = HuggingFaceEmbeddings(
|
| 82 |
+
model_name=EMBEDDING_MODEL_NAME,
|
| 83 |
model_kwargs={'device': 'cpu'},
|
| 84 |
encode_kwargs={'normalize_embeddings': True}
|
| 85 |
)
|
|
|
|
| 89 |
embedding=embedding_model,
|
| 90 |
normalize_L2=True
|
| 91 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
# Load LLM
|
| 94 |
+
tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_NAME)
|
|
|
|
|
|
|
| 95 |
model = AutoModelForCausalLM.from_pretrained(
|
| 96 |
+
LLM_MODEL_NAME,
|
| 97 |
device_map="auto",
|
| 98 |
torch_dtype=torch.float16,
|
| 99 |
trust_remote_code=True
|
| 100 |
)
|
|
|
|
| 101 |
|
| 102 |
+
pipe = pipeline(
|
| 103 |
+
"text-generation",
|
| 104 |
+
model=model,
|
| 105 |
+
tokenizer=tokenizer,
|
| 106 |
+
max_new_tokens=250,
|
| 107 |
+
temperature=0.7,
|
| 108 |
+
top_p=0.9,
|
| 109 |
+
repetition_penalty=1.1,
|
| 110 |
+
do_sample=True,
|
| 111 |
+
return_full_text=False,
|
| 112 |
+
pad_token_id=tokenizer.eos_token_id
|
| 113 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
# Setup QA chain
|
| 116 |
+
template = """<context>
|
| 117 |
+
{context}
|
| 118 |
+
</context>
|
| 119 |
|
| 120 |
+
<question>
|
| 121 |
+
{question}
|
| 122 |
+
</question>
|
| 123 |
|
| 124 |
+
Analyze the philosophical concept using ONLY the provided context. Follow these steps:
|
| 125 |
+
1. Identify key elements from the context
|
| 126 |
+
2. Explain relationships between concepts
|
| 127 |
+
3. Highlight any mentioned philosophical implications
|
| 128 |
|
| 129 |
+
If context is insufficient, state: "This requires deeper analysis beyond current knowledge."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
Answer:"""
|
| 132 |
+
|
| 133 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 134 |
+
llm=HuggingFacePipeline(pipeline=pipe),
|
| 135 |
+
chain_type="stuff",
|
| 136 |
+
retriever=vector_store.as_retriever(
|
| 137 |
+
search_type="similarity_score_threshold",
|
| 138 |
+
search_kwargs={
|
| 139 |
+
"k": 6,
|
| 140 |
+
"score_threshold": 0.55,
|
| 141 |
+
"include_metadata": True
|
| 142 |
+
}
|
| 143 |
+
),
|
| 144 |
+
return_source_documents=True,
|
| 145 |
+
chain_type_kwargs={
|
| 146 |
+
"prompt": PromptTemplate(
|
| 147 |
+
template=template,
|
| 148 |
+
input_variables=["context", "question"],
|
| 149 |
+
template_format="f-string"
|
| 150 |
+
)
|
| 151 |
+
},
|
| 152 |
+
verbose=True
|
| 153 |
+
)
|
| 154 |
+
return qa_chain
|
| 155 |
|
| 156 |
+
# ------ Unified Interface ------
|
| 157 |
+
def create_interface():
|
| 158 |
+
qa_chain = setup_rag_system()
|
|
|
|
| 159 |
|
| 160 |
+
with gr.Blocks(title="Philosophical AI Assistant") as demo:
|
| 161 |
+
gr.Markdown("# 🤖 AI Philosophy Assistant")
|
| 162 |
+
gr.Markdown("Combining conversational AI with philosophical knowledge base")
|
| 163 |
|
| 164 |
+
# Chat Tab
|
| 165 |
+
with gr.Tab("Chat"):
|
| 166 |
+
gr.ChatInterface(
|
| 167 |
+
fn=chat_respond,
|
| 168 |
+
additional_inputs=[
|
| 169 |
+
gr.Textbox(value="You are a philosophy expert assistant.", label="System Role"),
|
| 170 |
+
gr.Slider(1, 2048, value=512, label="Max Tokens"),
|
| 171 |
+
gr.Slider(0.1, 4.0, value=0.7, label="Temperature"),
|
| 172 |
+
gr.Slider(0.1, 1.0, value=0.95, label="Top-p")
|
| 173 |
+
],
|
| 174 |
+
chatbot=gr.Chatbot(height=500, avatar_images=("👤", "🤖")),
|
| 175 |
+
textbox=gr.Textbox(placeholder="Ask me anything about philosophy...", container=False, scale=7),
|
| 176 |
+
)
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
+
# Research Assistant Tab
|
| 179 |
+
with gr.Tab("Research Assistant"):
|
| 180 |
+
with gr.Row():
|
| 181 |
+
with gr.Column(scale=3):
|
| 182 |
+
query_input = gr.Textbox(label="Research Query", lines=3)
|
| 183 |
+
submit_btn = gr.Button("Analyze", variant="primary")
|
| 184 |
+
with gr.Column(scale=2):
|
| 185 |
+
sources_output = gr.Markdown(label="Source Context")
|
| 186 |
+
response_output = gr.Markdown(label="Analysis Results")
|
| 187 |
|
| 188 |
+
def process_query(query):
|
| 189 |
+
try:
|
| 190 |
+
result = qa_chain({"query": query})
|
| 191 |
+
response = result['result'].split("Answer:")[-1].strip()
|
| 192 |
+
sources = "\n".join(
|
| 193 |
+
f"**Source {i+1}:** {doc.page_content[:200]}..."
|
| 194 |
+
for i, doc in enumerate(result['source_documents'][:3])
|
| 195 |
+
)
|
| 196 |
+
return response, sources
|
| 197 |
+
except Exception as e:
|
| 198 |
+
return f"Error: {str(e)}", ""
|
| 199 |
+
|
| 200 |
+
submit_btn.click(
|
| 201 |
+
process_query,
|
| 202 |
+
inputs=query_input,
|
| 203 |
+
outputs=[response_output, sources_output]
|
| 204 |
+
)
|
| 205 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
return demo
|
| 207 |
|
|
|
|
| 208 |
if __name__ == "__main__":
|
| 209 |
+
demo = create_interface()
|
| 210 |
+
demo.launch(share=True)
|