|
|
|
from fuzzywuzzy import fuzz |
|
import re |
|
|
|
def extract_keyword(text: str, symptoms: list = None) -> str: |
|
""" |
|
Extracts a primary keyword from a given text, prioritizing symptom matches if available, |
|
otherwise, the first relevant word. |
|
Handles both "Question: " prefixed strings and direct symptom strings. |
|
""" |
|
if text.startswith("Question: "): |
|
|
|
question = text[10:].strip() |
|
words = question.split() |
|
if not words: |
|
return "Unknown" |
|
|
|
|
|
common_words = { |
|
'what', 'is', 'are', 'how', 'why', 'can', 'do', 'does', 'i', 'have', 'my', 'a', 'an', 'the', |
|
'in', 'of', 'and', 'or', 'for', 'with', 'from', 'about', 'some', 'any', 'this', 'that', |
|
'there', 'be', 'to', 'me', 'am', 'feel', 'feeling', 'experiencing', 'symptoms', 'issue', |
|
'problem', 'cause', 'causes', 'tell', 'me', 'more', 'information', 'on', 'about', 'a', |
|
'an', 'the', 'my', 'your', 'its', 'their', 'our', 'his', 'her', 'its', 'them', 'us', 'you', |
|
'i', 'we', 'he', 'she', 'it', 'they', 'this', 'that', 'these', 'those', 'which', 'who', |
|
'whom', 'whose', 'where', 'when', 'why', 'how', 'what', 'if', 'then', 'else', 'or', 'and', |
|
'but', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', |
|
'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', |
|
'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', |
|
'here', 'there', 'when', 'where', 'why', 'all', 'any', 'both', 'each', 'few', 'more', 'most', |
|
'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', |
|
'very', 's', 't', 'can', 'will', 'just', 'don', 'should', 'now' |
|
} |
|
|
|
|
|
if symptoms: |
|
best_match = None |
|
highest_score = 0 |
|
|
|
for symptom_phrase in sorted(symptoms, key=len, reverse=True): |
|
for i in range(len(words)): |
|
for j in range(i + 1, len(words) + 1): |
|
phrase_from_question = " ".join(words[i:j]).lower() |
|
score = fuzz.token_sort_ratio(phrase_from_question, symptom_phrase.lower()) |
|
if score > 85 and score > highest_score: |
|
best_match = symptom_phrase |
|
highest_score = score |
|
if best_match: |
|
return best_match.capitalize() |
|
|
|
|
|
for word in words: |
|
word_lower = word.lower() |
|
if word_lower not in common_words and len(word_lower) > 2: |
|
if not re.match(r'^\d+$', word_lower) and not re.match(r'^\w$', word_lower): |
|
return word.capitalize() |
|
|
|
|
|
for word in words: |
|
word_lower = word.lower() |
|
if word_lower not in common_words: |
|
return word.capitalize() |
|
|
|
return words[0].capitalize() if words else "Unknown" |
|
else: |
|
|
|
|
|
symptom_list_str = text.strip() |
|
if symptom_list_str: |
|
|
|
if len(symptom_list_str.split(',')) <= 3: |
|
return symptom_list_str.capitalize() |
|
else: |
|
first_symptom = symptom_list_str.split(',')[0].strip() |
|
return first_symptom.capitalize() |
|
return "Unknown" |