Spaces:
Sleeping
Sleeping
findEthics commited on
Commit ·
2d4c5b0
1
Parent(s): 2f04507
Spacy for getting search terms
Browse files- app.py +76 -0
- requirements.txt +5 -1
app.py
CHANGED
|
@@ -8,6 +8,11 @@ from typing import Optional, List, Dict, Any
|
|
| 8 |
import logging
|
| 9 |
import re
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
# Configure logging
|
| 12 |
logging.basicConfig(level=logging.INFO)
|
| 13 |
logger = logging.getLogger(__name__)
|
|
@@ -48,6 +53,63 @@ classifier_pipeline = None
|
|
| 48 |
qa_pipeline = None
|
| 49 |
summarization_pipeline = None
|
| 50 |
ner_pipeline = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
def load_classifier():
|
| 53 |
"""Load zero-shot classification model"""
|
|
@@ -146,10 +208,24 @@ async def startup_event():
|
|
| 146 |
load_classifier()
|
| 147 |
load_ner_model()
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
@app.post("/chat", response_model=ChatResponse)
|
| 150 |
async def chat_endpoint(request: ChatRequest):
|
| 151 |
"""Enhanced chat endpoint with dynamic model selection"""
|
|
|
|
| 152 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
search_results = []
|
| 154 |
search_context = ""
|
| 155 |
|
|
|
|
| 8 |
import logging
|
| 9 |
import re
|
| 10 |
|
| 11 |
+
|
| 12 |
+
import spacy
|
| 13 |
+
from rake_nltk import Rake
|
| 14 |
+
import nltk
|
| 15 |
+
|
| 16 |
# Configure logging
|
| 17 |
logging.basicConfig(level=logging.INFO)
|
| 18 |
logger = logging.getLogger(__name__)
|
|
|
|
| 53 |
qa_pipeline = None
|
| 54 |
summarization_pipeline = None
|
| 55 |
ner_pipeline = None
|
| 56 |
+
nlp = spacy.load("en_core_web_sm")
|
| 57 |
+
rake = Rake()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
############# SPACY TEST
|
| 61 |
+
|
| 62 |
+
def extract_search_terms(text: str) -> List[str]:
|
| 63 |
+
"""Extract enhanced search terms using combined NER, syntax, and keywords"""
|
| 64 |
+
doc = nlp(text)
|
| 65 |
+
|
| 66 |
+
# 1. Extract named entities
|
| 67 |
+
entities = [ent.text for ent in doc.ents]
|
| 68 |
+
|
| 69 |
+
# 2. Extract noun phrases through syntactic analysis
|
| 70 |
+
noun_phrases = list(doc.noun_chunks)
|
| 71 |
+
|
| 72 |
+
# 3. Extract question focus using dependency parsing
|
| 73 |
+
focus_phrase = extract_focus_phrase(doc)
|
| 74 |
+
|
| 75 |
+
# 4. Get keywords using RAKE
|
| 76 |
+
rake.extract_keywords_from_text(text)
|
| 77 |
+
keywords = rake.get_ranked_phrases()[:3] # Top 3 keywords
|
| 78 |
+
|
| 79 |
+
# Combine and filter terms
|
| 80 |
+
terms = entities + [np.text for np in noun_phrases] + keywords
|
| 81 |
+
if focus_phrase:
|
| 82 |
+
terms.append(focus_phrase)
|
| 83 |
+
|
| 84 |
+
# Clean and deduplicate
|
| 85 |
+
return clean_terms(terms)
|
| 86 |
+
|
| 87 |
+
def extract_focus_phrase(doc) -> str:
|
| 88 |
+
"""Extract main question focus using dependency parse"""
|
| 89 |
+
for token in doc:
|
| 90 |
+
if token.dep_ == "ROOT":
|
| 91 |
+
for child in token.children:
|
| 92 |
+
if child.dep_ in ("attr", "nsubj", "dobj"):
|
| 93 |
+
return " ".join([t.text for t in child.subtree])
|
| 94 |
+
return ""
|
| 95 |
+
|
| 96 |
+
def clean_terms(terms: List[str]) -> List[str]:
|
| 97 |
+
"""Remove duplicates and irrelevant terms"""
|
| 98 |
+
# Remove stopwords and single characters
|
| 99 |
+
cleaned = [
|
| 100 |
+
t for t in terms
|
| 101 |
+
if len(t) > 1 and not all(token.is_stop for token in nlp(t))
|
| 102 |
+
]
|
| 103 |
+
|
| 104 |
+
# Remove redundant subphrases
|
| 105 |
+
final_terms = []
|
| 106 |
+
for term in sorted(cleaned, key=len, reverse=True):
|
| 107 |
+
if not any(term in other for other in final_terms):
|
| 108 |
+
final_terms.append(term)
|
| 109 |
+
|
| 110 |
+
return final_terms
|
| 111 |
+
|
| 112 |
+
###############
|
| 113 |
|
| 114 |
def load_classifier():
|
| 115 |
"""Load zero-shot classification model"""
|
|
|
|
| 208 |
load_classifier()
|
| 209 |
load_ner_model()
|
| 210 |
|
| 211 |
+
try:
|
| 212 |
+
nltk.download('stopwords')
|
| 213 |
+
nltk.download('punkt_tab')
|
| 214 |
+
except Exception as e:
|
| 215 |
+
logger.error(f"NLTK download error: {e}")
|
| 216 |
+
|
| 217 |
@app.post("/chat", response_model=ChatResponse)
|
| 218 |
async def chat_endpoint(request: ChatRequest):
|
| 219 |
"""Enhanced chat endpoint with dynamic model selection"""
|
| 220 |
+
|
| 221 |
try:
|
| 222 |
+
spacy_search = extract_search_terms(request.prompt.lower())
|
| 223 |
+
logger.info(f"Extracted search terms using Spacy: {spacy_search}")
|
| 224 |
+
except Exception as e:
|
| 225 |
+
logger.error(f"Error extracting search terms using Spacy: {e}")
|
| 226 |
+
|
| 227 |
+
try:
|
| 228 |
+
|
| 229 |
search_results = []
|
| 230 |
search_context = ""
|
| 231 |
|
requirements.txt
CHANGED
|
@@ -7,4 +7,8 @@ accelerate==0.24.0
|
|
| 7 |
duckduckgo-search
|
| 8 |
requests==2.31.0
|
| 9 |
python-multipart==0.0.6
|
| 10 |
-
keras
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
duckduckgo-search
|
| 8 |
requests==2.31.0
|
| 9 |
python-multipart==0.0.6
|
| 10 |
+
keras
|
| 11 |
+
rake_nltk
|
| 12 |
+
nltk
|
| 13 |
+
spacy
|
| 14 |
+
en_core_web_sm @ https://huggingface.co/spacy/en_core_web_sm/resolve/main/en_core_web_sm-any-py3-none-any.whl
|