Spaces:
Build error
Build error
Test push
Browse files
app.py
CHANGED
|
@@ -2,7 +2,7 @@ import gradio as gr
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
|
| 4 |
"""
|
| 5 |
-
For information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
| 6 |
"""
|
| 7 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 8 |
|
|
@@ -60,5 +60,209 @@ demo = gr.ChatInterface(
|
|
| 60 |
)
|
| 61 |
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
if __name__ == "__main__":
|
| 64 |
-
demo
|
|
|
|
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
|
| 4 |
"""
|
| 5 |
+
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
| 6 |
"""
|
| 7 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 8 |
|
|
|
|
| 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 |
+
try:
|
| 79 |
+
df = pd.read_csv(csv_path)
|
| 80 |
+
|
| 81 |
+
if 'Cleaned_Ideas' not in df.columns or 'Embeddings' not in df.columns:
|
| 82 |
+
raise ValueError("CSV must contain 'Cleaned_Ideas' and 'Embeddings' columns")
|
| 83 |
+
|
| 84 |
+
df['Embeddings'] = df['Embeddings'].apply(
|
| 85 |
+
lambda x: np.fromstring(
|
| 86 |
+
x.strip("[]").replace("\n", ""),
|
| 87 |
+
sep=", ",
|
| 88 |
+
dtype=np.float32
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
expected_dim = 768
|
| 93 |
+
valid_embeddings = df['Embeddings'].apply(lambda x: len(x) == expected_dim)
|
| 94 |
+
if not valid_embeddings.all():
|
| 95 |
+
invalid_count = len(df) - valid_embeddings.sum()
|
| 96 |
+
raise ValueError(f"{invalid_count} entries have invalid embedding dimensions")
|
| 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="sentence-transformers/all-mpnet-base-v2",
|
| 111 |
+
model_kwargs={'device': 'cpu'},
|
| 112 |
+
encode_kwargs={'normalize_embeddings': True}
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
vector_store = FAISS.from_embeddings(
|
| 116 |
+
text_embeddings=list(zip(texts, embeddings)),
|
| 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 |
+
# 3. Using an openly available model (GPT-Neo 1.3B)
|
| 127 |
+
model_name = "EleutherAI/gpt-neo-1.3B"
|
| 128 |
+
try:
|
| 129 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 130 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 131 |
+
model_name,
|
| 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 |
+
except Exception as e:
|
| 139 |
+
print(f"Model loading failed: {str(e)}")
|
| 140 |
+
print("You may need to accept the model license at: https://huggingface.co/EleutherAI/gpt-neo-1.3B")
|
| 141 |
+
raise
|
| 142 |
+
|
| 143 |
+
# Text generation pipeline
|
| 144 |
+
pipe = pipeline(
|
| 145 |
+
"text-generation",
|
| 146 |
+
model=model,
|
| 147 |
+
tokenizer=tokenizer,
|
| 148 |
+
max_new_tokens=250,
|
| 149 |
+
temperature=0.7,
|
| 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 |
+
Analyze the philosophical concept using ONLY the provided context. Follow these steps:
|
| 169 |
+
1. Identify key elements from the context
|
| 170 |
+
2. Explain relationships between concepts
|
| 171 |
+
3. Highlight any mentioned philosophical implications
|
| 172 |
+
|
| 173 |
+
If context is insufficient, state: "This requires deeper analysis beyond current knowledge."
|
| 174 |
+
|
| 175 |
+
Answer:"""
|
| 176 |
+
|
| 177 |
+
prompt = PromptTemplate(
|
| 178 |
+
template=template,
|
| 179 |
+
input_variables=["context", "question"],
|
| 180 |
+
template_format="f-string"
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# 5. Optimized retrieval configuration
|
| 184 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 185 |
+
llm=llm,
|
| 186 |
+
chain_type="stuff",
|
| 187 |
+
retriever=vector_store.as_retriever(
|
| 188 |
+
search_type="similarity_score_threshold",
|
| 189 |
+
search_kwargs={
|
| 190 |
+
"k": 6,
|
| 191 |
+
"score_threshold": 0.55,
|
| 192 |
+
"include_metadata": True
|
| 193 |
+
}
|
| 194 |
+
),
|
| 195 |
+
return_source_documents=True,
|
| 196 |
+
chain_type_kwargs={
|
| 197 |
+
"prompt": prompt,
|
| 198 |
+
"document_prompt": PromptTemplate(
|
| 199 |
+
input_variables=["page_content"],
|
| 200 |
+
template="{page_content}"
|
| 201 |
+
)
|
| 202 |
+
},
|
| 203 |
+
verbose=True
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# 6. Query processing function
|
| 207 |
+
def process_query(query):
|
| 208 |
+
if not query.strip():
|
| 209 |
+
return "Please enter a valid question", ""
|
| 210 |
+
|
| 211 |
+
try:
|
| 212 |
+
result = qa_chain({"query": query})
|
| 213 |
+
response = result['result'].split("Answer:")[-1].strip()
|
| 214 |
+
|
| 215 |
+
sources_info = "\n\n**Sources:**\n"
|
| 216 |
+
for i, doc in enumerate(result['source_documents'][:3], 1):
|
| 217 |
+
excerpt = doc.page_content[:200].replace("\n", " ") + "..."
|
| 218 |
+
score = doc.metadata.get('score', 0)
|
| 219 |
+
sources_info += f"{i}. {excerpt} (Relevance: {score:.2f})\n\n"
|
| 220 |
+
|
| 221 |
+
return response, sources_info
|
| 222 |
+
|
| 223 |
+
except Exception as e:
|
| 224 |
+
return f"Error processing request: {str(e)}", ""
|
| 225 |
+
|
| 226 |
+
# 7. Gradio interface
|
| 227 |
+
def create_gradio_interface():
|
| 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 |
+
with gr.Row():
|
| 233 |
+
with gr.Column(scale=4):
|
| 234 |
+
query_input = gr.Textbox(
|
| 235 |
+
label="Your Question",
|
| 236 |
+
placeholder="Ask about philosophical concepts...",
|
| 237 |
+
lines=3
|
| 238 |
+
)
|
| 239 |
+
submit_btn = gr.Button("Analyze", variant="primary")
|
| 240 |
+
|
| 241 |
+
with gr.Row():
|
| 242 |
+
with gr.Column(scale=3):
|
| 243 |
+
response_output = gr.Markdown(label="Analysis")
|
| 244 |
+
with gr.Column(scale=2):
|
| 245 |
+
sources_output = gr.Markdown(label="Supporting Context")
|
| 246 |
+
|
| 247 |
+
submit_btn.click(
|
| 248 |
+
fn=process_query,
|
| 249 |
+
inputs=[query_input],
|
| 250 |
+
outputs=[response_output, sources_output]
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
gr.Markdown("## Example Queries")
|
| 254 |
+
examples = gr.Examples(
|
| 255 |
+
examples=[
|
| 256 |
+
["Explain the relationship between consciousness and reality using the provided context"],
|
| 257 |
+
["How does the concept of 'being' differ across philosophical traditions?"],
|
| 258 |
+
["Analyze the arguments for and against epistemological dualism"]
|
| 259 |
+
],
|
| 260 |
+
inputs=query_input
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
return demo
|
| 264 |
+
|
| 265 |
+
# 8. Launch the interface
|
| 266 |
if __name__ == "__main__":
|
| 267 |
+
demo = create_gradio_interface()
|
| 268 |
+
demo.launch(share=True)
|