findEthics commited on
Commit
00fd6a4
·
1 Parent(s): c50b7d8

Use spacy for summarizer preprocessing

Browse files
Files changed (1) hide show
  1. app.py +22 -18
app.py CHANGED
@@ -58,9 +58,6 @@ summarization_pipeline = None
58
  nlp = spacy.load("en_core_web_sm")
59
  rake = Rake()
60
 
61
-
62
- ############# SPACY TEST
63
-
64
  def extract_search_terms(text: str) -> List[str]:
65
  """Extract enhanced search terms using combined NER, syntax, and keywords"""
66
  doc = nlp(text)
@@ -111,8 +108,6 @@ def clean_terms(terms: List[str]) -> List[str]:
111
 
112
  return final_terms
113
 
114
- ###############
115
-
116
  def load_classifier():
117
  """Load zero-shot classification model"""
118
  global classifier_pipeline
@@ -184,11 +179,20 @@ def search_web(query: str, max_results: int = 5) -> List[Dict[str, Any]]:
184
 
185
  def format_search_context(results: List[Dict[str, Any]]) -> str:
186
  """Create condensed context from search results"""
187
- return "\n".join(
188
  f"{i+1}. {res['title']}: {res['body'][:200]}"
189
  for i, res in enumerate(results[:5])
190
  )
191
 
 
 
 
 
 
 
 
 
 
192
  @app.on_event("startup")
193
  async def startup_event():
194
  """Initialize core models on startup"""
@@ -197,7 +201,7 @@ async def startup_event():
197
  @app.post("/chat", response_model=ChatResponse)
198
  async def chat_endpoint(request: ChatRequest):
199
  """Enhanced chat endpoint with dynamic model selection"""
200
-
201
  try:
202
  search_results = []
203
  search_context = ""
@@ -229,18 +233,18 @@ async def chat_endpoint(request: ChatRequest):
229
  if not summarization_pipeline:
230
  load_summarization_model()
231
  # Handle long contexts safely
232
- inputs = summarization_pipeline.tokenizer(
233
- search_context or request.prompt,
234
- truncation=True,
235
- max_length=1024,
236
- return_tensors="pt"
237
- )
238
- processed_context = summarization_pipeline.tokenizer.decode(
239
- inputs['input_ids'][0],
240
- skip_special_tokens=True
241
- )
242
  response = summarization_pipeline(
243
- processed_context,
244
  max_length=150,
245
  min_length=30,
246
  do_sample=False
 
58
  nlp = spacy.load("en_core_web_sm")
59
  rake = Rake()
60
 
 
 
 
61
  def extract_search_terms(text: str) -> List[str]:
62
  """Extract enhanced search terms using combined NER, syntax, and keywords"""
63
  doc = nlp(text)
 
108
 
109
  return final_terms
110
 
 
 
111
  def load_classifier():
112
  """Load zero-shot classification model"""
113
  global classifier_pipeline
 
179
 
180
  def format_search_context(results: List[Dict[str, Any]]) -> str:
181
  """Create condensed context from search results"""
182
+ return "\n".join(
183
  f"{i+1}. {res['title']}: {res['body'][:200]}"
184
  for i, res in enumerate(results[:5])
185
  )
186
 
187
+ def preprocess_text(text: str) -> str:
188
+ """Use spaCy for fast text cleaning/normalization"""
189
+ doc = nlp(text)
190
+ # Lemmatize and remove stopwords
191
+ return " ".join([
192
+ token.lemma_ for token in doc
193
+ if not token.is_stop and not token.is_punct
194
+ ])[:1024]
195
+
196
  @app.on_event("startup")
197
  async def startup_event():
198
  """Initialize core models on startup"""
 
201
  @app.post("/chat", response_model=ChatResponse)
202
  async def chat_endpoint(request: ChatRequest):
203
  """Enhanced chat endpoint with dynamic model selection"""
204
+ logger.info(f"Request: {request.prompt}")
205
  try:
206
  search_results = []
207
  search_context = ""
 
233
  if not summarization_pipeline:
234
  load_summarization_model()
235
  # Handle long contexts safely
236
+ # inputs = summarization_pipeline.tokenizer(
237
+ # search_context or request.prompt,
238
+ # truncation=True,
239
+ # max_length=1024,
240
+ # return_tensors="pt"
241
+ # )
242
+ # processed_context = summarization_pipeline.tokenizer.decode(
243
+ # inputs['input_ids'][0],
244
+ # skip_special_tokens=True
245
+ # )
246
  response = summarization_pipeline(
247
+ preprocess_text(search_context.lower() or request.prompt.lower()),
248
  max_length=150,
249
  min_length=30,
250
  do_sample=False