Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,80 @@
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from huggingface_hub import InferenceClient
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
"""
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
)
|
18 |
-
|
|
|
|
|
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 |
-
|
|
|
|
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
|
39 |
-
|
40 |
-
|
|
|
41 |
|
|
|
|
|
|
|
|
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
],
|
|
|
|
|
60 |
)
|
61 |
|
62 |
|
63 |
-
if __name__ == "__main__":
|
64 |
-
demo.launch()
|
|
|
1 |
+
import os
|
2 |
+
import pandas as pd
|
3 |
+
import google.generativeai as genai
|
4 |
+
import numpy as np
|
5 |
import gradio as gr
|
|
|
6 |
|
7 |
+
# Initialize an empty DataFrame with columns 'Title' and 'Text'
|
8 |
+
df = pd.DataFrame(columns=['Title', 'Text'])
|
|
|
|
|
9 |
|
10 |
+
# Mapping filenames to custom titles
|
11 |
+
title_mapping = {
|
12 |
+
'company.txt': 'company_data',
|
13 |
+
'products.txt': 'product_data',
|
14 |
+
'shipping.txt': 'shipping_data'
|
15 |
+
}
|
16 |
|
17 |
+
# Loop through each file in the current directory and process the relevant ones
|
18 |
+
for file_name in os.listdir('.'):
|
19 |
+
if file_name in title_mapping:
|
20 |
+
try:
|
21 |
+
with open(file_name, 'r', encoding='utf-8') as file:
|
22 |
+
text = file.read().replace('\n', ' ') # Replace newlines with spaces for cleaner text
|
23 |
+
custom_title = title_mapping[file_name]
|
24 |
+
new_row = pd.DataFrame({'Title': [custom_title], 'Text': [text]})
|
25 |
+
df = pd.concat([df, new_row], ignore_index=True)
|
26 |
+
except Exception as e:
|
27 |
+
print(f"Error processing file {file_name}: {e}")
|
28 |
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
+
GEMINI_API_KEY = os.getenv("GOOGLE_API_KEY")
|
31 |
+
if not GEMINI_API_KEY:
|
32 |
+
return "Error: Gemini API key not found. Please set the GEMINI_API_KEY environment variable."
|
33 |
|
34 |
+
# Configure the Gemini API
|
35 |
+
try:
|
36 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
37 |
+
except Exception as e:
|
38 |
+
return f"Error: Failed to configure the Gemini API. Details: {e}"
|
39 |
|
40 |
+
# Function to embed text using the Google Generative AI API
|
41 |
+
def embed_text(text):
|
42 |
+
return genai.embed_content(model='models/embedding-001', content=text, task_type='retrieval_document')['embedding']
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
+
# Embed the text and ensure embeddings are stored in the DataFrame
|
45 |
+
if 'Embeddings' not in df.columns:
|
46 |
+
df['Embeddings'] = df['Text'].apply(embed_text)
|
47 |
|
48 |
+
# Function to calculate similarity score between the query and document embeddings
|
49 |
+
def query_similarity_score(query, vector):
|
50 |
+
query_embedding = embed_text(query)
|
51 |
+
return np.dot(query_embedding, vector)
|
52 |
|
53 |
+
# Function to get the most similar document based on the query
|
54 |
+
def most_similar_document(query):
|
55 |
+
# Create a local DataFrame copy to store similarity scores
|
56 |
+
local_df = df.copy()
|
57 |
+
# Calculate similarity for all rows
|
58 |
+
local_df['Similarity'] = local_df['Embeddings'].apply(lambda vector: query_similarity_score(query, vector))
|
59 |
+
# Sort by similarity score and retrieve the top match
|
60 |
+
most_similar = local_df.sort_values('Similarity', ascending=False).iloc[0]
|
61 |
+
return most_similar['Title'], most_similar['Text']
|
62 |
+
|
63 |
+
# Function to generate a response using the RAG approach
|
64 |
+
def RAG(query):
|
65 |
+
title, text = most_similar_document(query)
|
66 |
+
model = genai.GenerativeModel('gemini-pro')
|
67 |
+
prompt = f"Answer this query:\n{query}.\nOnly use this context to answer:\n{text}"
|
68 |
+
response = model.generate_content(prompt)
|
69 |
+
return f"{response.text}\n\nSource Document: {title}"
|
70 |
+
|
71 |
+
iface = gr.Interface(
|
72 |
+
fn=RAG, # Main function to handle the query
|
73 |
+
inputs=[
|
74 |
+
gr.Textbox(label="Enter Your Query"), # Input for the user's query
|
75 |
],
|
76 |
+
outputs=gr.Textbox(label="Response"), # Output for the generated response
|
77 |
+
title="Patrick's Multilingual Query Handler"
|
78 |
)
|
79 |
|
80 |
|
|
|
|