Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -26,103 +26,45 @@ embeddings = VoyageAIEmbeddings(voyage_api_key=voyage_api_key, model="voyage-law
|
|
| 26 |
# ๐น Query Expansion using GPT-4
|
| 27 |
def expand_query(query):
|
| 28 |
llm = ChatOpenAI(model="gpt-4", openai_api_key=openai.api_key, temperature=0.3)
|
| 29 |
-
prompt = f"Rewrite this vague query
|
| 30 |
refined_query = llm([HumanMessage(content=prompt)]).content.strip()
|
| 31 |
return refined_query if refined_query else query
|
| 32 |
|
| 33 |
# ๐น Hybrid Search (TF-IDF + Semantic Retrieval)
|
| 34 |
-
# def hybrid_search(query, user_groups, index_name="briefmeta", min_score=0.01, fetch_k=50):
|
| 35 |
-
# vector_store = PineconeVectorStore(index_name=index_name, embedding=embeddings)
|
| 36 |
-
# semantic_results = vector_store.max_marginal_relevance_search(query, k=10, fetch_k=fetch_k)
|
| 37 |
-
|
| 38 |
-
# all_texts = [doc.page_content for doc in semantic_results]
|
| 39 |
-
# vectorizer = TfidfVectorizer(stop_words="english")
|
| 40 |
-
# tfidf_matrix = vectorizer.fit_transform(all_texts)
|
| 41 |
-
# query_tfidf = vectorizer.transform([query])
|
| 42 |
-
# keyword_scores = cosine_similarity(query_tfidf, tfidf_matrix).flatten()
|
| 43 |
-
|
| 44 |
-
# combined_results, seen_ids = [], set()
|
| 45 |
-
# for i, doc in enumerate(semantic_results):
|
| 46 |
-
# doc_id, doc_groups = doc.metadata.get("id"), doc.metadata.get("groups", [])
|
| 47 |
-
# semantic_score = float(doc.metadata.get("score", 0))
|
| 48 |
-
# keyword_score = float(keyword_scores[i])
|
| 49 |
-
# final_score = 0.65 * semantic_score + 0.35 * keyword_score # Hybrid score
|
| 50 |
-
|
| 51 |
-
# if doc_id not in seen_ids and any(group in user_groups for group in doc_groups) and final_score > min_score:
|
| 52 |
-
# seen_ids.add(doc_id)
|
| 53 |
-
# doc.metadata["final_score"] = final_score
|
| 54 |
-
# combined_results.append(doc)
|
| 55 |
-
|
| 56 |
-
# combined_results.sort(key=lambda x: x.metadata["final_score"], reverse=True)
|
| 57 |
-
# return [
|
| 58 |
-
# {
|
| 59 |
-
# "doc_id": doc.metadata.get("doc_id", "N/A"),
|
| 60 |
-
# "chunk_id": doc.metadata.get("id", "N/A"),
|
| 61 |
-
# "title": doc.metadata.get("source", "N/A"),
|
| 62 |
-
# "text": doc.page_content,
|
| 63 |
-
# "page_number": str(doc.metadata.get("page_number", "N/A")),
|
| 64 |
-
# "score": str(doc.metadata.get("final_score", "N/A")),
|
| 65 |
-
# }
|
| 66 |
-
# for doc in combined_results
|
| 67 |
-
# ]
|
| 68 |
-
|
| 69 |
def hybrid_search(query, user_groups, index_name="briefmeta", min_score=0.01, fetch_k=50):
|
| 70 |
vector_store = PineconeVectorStore(index_name=index_name, embedding=embeddings)
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
if doc_id not in seen_ids and final_score > min_score:
|
| 105 |
-
seen_ids.add(doc_id)
|
| 106 |
-
doc.metadata["final_score"] = final_score
|
| 107 |
-
combined_results.append(doc)
|
| 108 |
-
|
| 109 |
-
# **5๏ธโฃ Sort Results by Final Score**
|
| 110 |
-
combined_results.sort(key=lambda x: x.metadata["final_score"], reverse=True)
|
| 111 |
-
|
| 112 |
-
return [
|
| 113 |
-
{
|
| 114 |
-
"doc_id": doc.metadata.get("doc_id", "N/A"),
|
| 115 |
-
"chunk_id": doc.metadata.get("id", "N/A"),
|
| 116 |
-
"title": doc.metadata.get("source", "N/A"),
|
| 117 |
-
"text": doc.page_content,
|
| 118 |
-
"page_number": str(doc.metadata.get("page_number", "N/A")),
|
| 119 |
-
"score": str(doc.metadata.get("final_score", "N/A")),
|
| 120 |
-
}
|
| 121 |
-
for doc in combined_results
|
| 122 |
-
]
|
| 123 |
-
except Exception as e:
|
| 124 |
-
print(e)
|
| 125 |
-
return
|
| 126 |
|
| 127 |
# ๐น Metadata-Weighted Reranking
|
| 128 |
def rerank(query, context):
|
|
@@ -133,9 +75,9 @@ def rerank(query, context):
|
|
| 133 |
final_reranked = []
|
| 134 |
for entry in reranker.data:
|
| 135 |
doc, score = entry["document"], float(entry["score"])
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
doc["final_score"] = final_score
|
| 140 |
final_reranked.append(doc)
|
| 141 |
|
|
@@ -143,24 +85,23 @@ def rerank(query, context):
|
|
| 143 |
return final_reranked
|
| 144 |
|
| 145 |
# ๐น Intelligent Search Summary Generator
|
| 146 |
-
def generate_search_summary(search_results,
|
| 147 |
if not search_results:
|
| 148 |
return "No relevant documents found. Try refining your query."
|
| 149 |
|
| 150 |
-
num_results = len(
|
| 151 |
doc_titles = [doc.get("title", "Unknown Document") for doc in search_results]
|
| 152 |
doc_pages = [doc.get("page_number", "N/A") for doc in search_results]
|
| 153 |
relevance_scores = [float(doc.get("score", 0)) for doc in search_results]
|
| 154 |
|
| 155 |
summary_prompt = f"""
|
| 156 |
-
Generate a concise 1-3 sentence summary
|
| 157 |
- User Query: "{query}"
|
| 158 |
- Matching Documents: {num_results} found
|
| 159 |
- Titles: {", ".join(set(doc_titles))}
|
| 160 |
- Pages Referenced: {", ".join(set(doc_pages))}
|
| 161 |
- Relevance Scores (0-1): {relevance_scores}
|
| 162 |
Provide a clear, user-friendly summary with an action suggestion.
|
| 163 |
-
If scores are low but the documents are from the same title no need to comment on the scores.
|
| 164 |
"""
|
| 165 |
|
| 166 |
llm = ChatOpenAI(model="gpt-4", openai_api_key=openai.api_key, temperature=0.5)
|
|
@@ -202,7 +143,7 @@ def complete_workflow(query, user_groups, index_name="briefmeta"):
|
|
| 202 |
|
| 203 |
document_titles = list({os.path.basename(doc["title"]) for doc in context_data})
|
| 204 |
formatted_titles = " " + "\n".join(document_titles)
|
| 205 |
-
intelligent_search_summary = generate_search_summary(context_data,
|
| 206 |
|
| 207 |
results = {
|
| 208 |
"results": [
|
|
|
|
| 26 |
# ๐น Query Expansion using GPT-4
|
| 27 |
def expand_query(query):
|
| 28 |
llm = ChatOpenAI(model="gpt-4", openai_api_key=openai.api_key, temperature=0.3)
|
| 29 |
+
prompt = f"Rewrite this vague query into a more specific one:\nQuery: {query}\nSpecific Query:"
|
| 30 |
refined_query = llm([HumanMessage(content=prompt)]).content.strip()
|
| 31 |
return refined_query if refined_query else query
|
| 32 |
|
| 33 |
# ๐น Hybrid Search (TF-IDF + Semantic Retrieval)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
def hybrid_search(query, user_groups, index_name="briefmeta", min_score=0.01, fetch_k=50):
|
| 35 |
vector_store = PineconeVectorStore(index_name=index_name, embedding=embeddings)
|
| 36 |
+
semantic_results = vector_store.max_marginal_relevance_search(query, k=10, fetch_k=fetch_k)
|
| 37 |
+
|
| 38 |
+
all_texts = [doc.page_content for doc in semantic_results]
|
| 39 |
+
vectorizer = TfidfVectorizer(stop_words="english")
|
| 40 |
+
tfidf_matrix = vectorizer.fit_transform(all_texts)
|
| 41 |
+
query_tfidf = vectorizer.transform([query])
|
| 42 |
+
keyword_scores = cosine_similarity(query_tfidf, tfidf_matrix).flatten()
|
| 43 |
+
|
| 44 |
+
combined_results, seen_ids = [], set()
|
| 45 |
+
for i, doc in enumerate(semantic_results):
|
| 46 |
+
doc_id, doc_groups = doc.metadata.get("id"), doc.metadata.get("groups", [])
|
| 47 |
+
semantic_score = float(doc.metadata.get("score", 0))
|
| 48 |
+
keyword_score = float(keyword_scores[i])
|
| 49 |
+
final_score = 0.7 * semantic_score + 0.3 * keyword_score # Hybrid score
|
| 50 |
+
|
| 51 |
+
if doc_id not in seen_ids and any(group in user_groups for group in doc_groups) and final_score > min_score:
|
| 52 |
+
seen_ids.add(doc_id)
|
| 53 |
+
doc.metadata["final_score"] = final_score
|
| 54 |
+
combined_results.append(doc)
|
| 55 |
+
|
| 56 |
+
combined_results.sort(key=lambda x: x.metadata["final_score"], reverse=True)
|
| 57 |
+
return [
|
| 58 |
+
{
|
| 59 |
+
"doc_id": doc.metadata.get("doc_id", "N/A"),
|
| 60 |
+
"chunk_id": doc.metadata.get("id", "N/A"),
|
| 61 |
+
"title": doc.metadata.get("source", "N/A"),
|
| 62 |
+
"text": doc.page_content,
|
| 63 |
+
"page_number": str(doc.metadata.get("page_number", "N/A")),
|
| 64 |
+
"score": str(doc.metadata.get("final_score", "N/A")),
|
| 65 |
+
}
|
| 66 |
+
for doc in combined_results
|
| 67 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
# ๐น Metadata-Weighted Reranking
|
| 70 |
def rerank(query, context):
|
|
|
|
| 75 |
final_reranked = []
|
| 76 |
for entry in reranker.data:
|
| 77 |
doc, score = entry["document"], float(entry["score"])
|
| 78 |
+
citation_boost = 1.2 if "high_citations" in doc.get("tags", []) else 1.0
|
| 79 |
+
recency_boost = 1.1 if "recent_upload" in doc.get("tags", []) else 1.0
|
| 80 |
+
final_score = score * citation_boost * recency_boost
|
| 81 |
doc["final_score"] = final_score
|
| 82 |
final_reranked.append(doc)
|
| 83 |
|
|
|
|
| 85 |
return final_reranked
|
| 86 |
|
| 87 |
# ๐น Intelligent Search Summary Generator
|
| 88 |
+
def generate_search_summary(search_results, query):
|
| 89 |
if not search_results:
|
| 90 |
return "No relevant documents found. Try refining your query."
|
| 91 |
|
| 92 |
+
num_results = len(search_results)
|
| 93 |
doc_titles = [doc.get("title", "Unknown Document") for doc in search_results]
|
| 94 |
doc_pages = [doc.get("page_number", "N/A") for doc in search_results]
|
| 95 |
relevance_scores = [float(doc.get("score", 0)) for doc in search_results]
|
| 96 |
|
| 97 |
summary_prompt = f"""
|
| 98 |
+
Generate a concise 1-3 sentence summary:
|
| 99 |
- User Query: "{query}"
|
| 100 |
- Matching Documents: {num_results} found
|
| 101 |
- Titles: {", ".join(set(doc_titles))}
|
| 102 |
- Pages Referenced: {", ".join(set(doc_pages))}
|
| 103 |
- Relevance Scores (0-1): {relevance_scores}
|
| 104 |
Provide a clear, user-friendly summary with an action suggestion.
|
|
|
|
| 105 |
"""
|
| 106 |
|
| 107 |
llm = ChatOpenAI(model="gpt-4", openai_api_key=openai.api_key, temperature=0.5)
|
|
|
|
| 143 |
|
| 144 |
document_titles = list({os.path.basename(doc["title"]) for doc in context_data})
|
| 145 |
formatted_titles = " " + "\n".join(document_titles)
|
| 146 |
+
intelligent_search_summary = generate_search_summary(context_data, refined_query)
|
| 147 |
|
| 148 |
results = {
|
| 149 |
"results": [
|