webtraffic commited on
Commit
2d0baf8
·
verified ·
1 Parent(s): 784d5a1

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +51 -20
main.py CHANGED
@@ -3,14 +3,15 @@ from pydantic import BaseModel
3
  import spacy
4
  from collections import Counter
5
  from fastapi.middleware.cors import CORSMiddleware
 
6
 
 
7
  nlp = spacy.load("en_core_web_sm")
8
- app = FastAPI(title="SEO Entity Extractor API")
9
 
10
  app.add_middleware(
11
  CORSMiddleware,
12
  allow_origins=["*"],
13
- allow_credentials=True,
14
  allow_methods=["*"],
15
  allow_headers=["*"],
16
  )
@@ -18,29 +19,59 @@ app.add_middleware(
18
  class TextPayload(BaseModel):
19
  text: str
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  @app.post("/analyze")
22
  async def analyze_text(payload: TextPayload):
23
  doc = nlp(payload.text)
24
- entities = []
25
- entity_freq = Counter([ent.text.lower() for ent in doc.ents if ent.text.strip()])
26
- total_entities = len(doc.ents)
27
 
28
- for ent in doc.ents:
29
- if not ent.text.strip():
30
- continue
31
- salience_proxy = entity_freq[ent.text.lower()] / total_entities if total_entities > 0 else 0
32
- entities.append({
33
- "text": ent.text.strip(),
34
- "label": ent.label_,
35
- "salience_score": round(salience_proxy, 4),
36
- "frequency": entity_freq[ent.text.lower()]
37
- })
38
-
39
- unique_entities = {v['text'].lower(): v for v in entities}.values()
40
- sorted_entities = sorted(list(unique_entities), key=lambda x: x['salience_score'], reverse=True)
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  return {
43
  "status": "success",
44
- "metrics": {"total_words": len(doc), "total_entities_found": len(sorted_entities)},
45
- "entities": sorted_entities
46
  }
 
3
  import spacy
4
  from collections import Counter
5
  from fastapi.middleware.cors import CORSMiddleware
6
+ import requests
7
 
8
+ # Load model
9
  nlp = spacy.load("en_core_web_sm")
10
+ app = FastAPI()
11
 
12
  app.add_middleware(
13
  CORSMiddleware,
14
  allow_origins=["*"],
 
15
  allow_methods=["*"],
16
  allow_headers=["*"],
17
  )
 
19
  class TextPayload(BaseModel):
20
  text: str
21
 
22
+ def get_wikidata_id(entity_text):
23
+ """Checks if the entity exists in the Knowledge Graph"""
24
+ url = "https://www.wikidata.org/w/api.php"
25
+ params = {
26
+ "action": "wbsearchentities",
27
+ "format": "json",
28
+ "language": "en",
29
+ "search": entity_text
30
+ }
31
+ try:
32
+ res = requests.get(url, params=params, timeout=2).json()
33
+ if res.get('search'):
34
+ # Return the first ID and the description to help with classification
35
+ return res['search'][0]['id'], res['search'][0].get('description', '')
36
+ except:
37
+ pass
38
+ return None, None
39
+
40
  @app.post("/analyze")
41
  async def analyze_text(payload: TextPayload):
42
  doc = nlp(payload.text)
 
 
 
43
 
44
+ # Filter: Only keep Nouns/Proper Nouns and entities with more than 2 characters
45
+ raw_entities = [ent for ent in doc.ents if len(ent.text) > 2]
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ entity_freq = Counter([ent.text.lower() for ent in raw_entities])
48
+ processed_entities = []
49
+ seen = set()
50
+
51
+ # Sort by frequency first to prioritize likely topics
52
+ for ent in raw_entities:
53
+ e_text = ent.text.strip()
54
+ e_lower = e_text.lower()
55
+
56
+ if e_lower not in seen:
57
+ # VALIDATION STEP: Check against Wikidata to remove noise like "daily" or "zero"
58
+ wid, desc = get_wikidata_id(e_text)
59
+
60
+ if wid: # If it exists in the Knowledge Graph
61
+ processed_entities.append({
62
+ "text": e_text,
63
+ "label": ent.label_,
64
+ "wikidata_id": wid,
65
+ "description": desc,
66
+ "salience_score": round(entity_freq[e_lower] / len(raw_entities), 4) if raw_entities else 0
67
+ })
68
+ seen.add(e_lower)
69
+
70
+ # Sort final list by salience
71
+ sorted_entities = sorted(processed_entities, key=lambda x: x['salience_score'], reverse=True)
72
+
73
  return {
74
  "status": "success",
75
+ "metrics": {"total_entities_found": len(sorted_entities)},
76
+ "entities": sorted_entities[:20] # Return top 20 clean entities
77
  }