adamaslan commited on
Commit
84dd0c3
·
1 Parent(s): 3a494ca

Test push3

Browse files
Files changed (1) hide show
  1. app.py +159 -217
app.py CHANGED
@@ -1,113 +1,85 @@
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
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
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
 
 
17
  ):
18
  messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
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 = message.choices[0].delta.content
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
- 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
  )
@@ -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
- # 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)
 
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)