j-higgins commited on
Commit
6189d82
·
2 Parent(s): 9cbde91 84b03e5

Resolve merge conflict in README.md

Browse files
Files changed (5) hide show
  1. Dockerfile +10 -0
  2. LICENSE +201 -0
  3. app.py +529 -0
  4. google_categories.txt +0 -0
  5. requirements.txt +9 -0
Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY . .
9
+
10
+ CMD ["python", "app.py"]
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
app.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dash
2
+ import dash_bootstrap_components as dbc
3
+ import pandas as pd
4
+ from dash import dcc, html, callback_context
5
+ from dash.dash_table import DataTable
6
+ from dash.dependencies import Output, Input, State
7
+ import plotly.express as px
8
+ import spacy
9
+ from sentence_transformers import SentenceTransformer
10
+ from sklearn.metrics.pairwise import cosine_similarity
11
+ from gliner_spacy.pipeline import GlinerSpacy
12
+ import warnings
13
+ import os
14
+ import gc
15
+
16
+ # Suppress specific warnings
17
+ warnings.filterwarnings("ignore", message="The sentencepiece tokenizer")
18
+
19
+ # Initialize Dash app
20
+ app = dash.Dash(__name__, external_stylesheets=[dbc.themes.DARKLY, 'https://use.fontawesome.com/releases/v5.8.1/css/all.css'])
21
+ server = app.server
22
+
23
+ # Reference absolute file path
24
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
25
+ CATEGORIES_FILE = os.path.join(BASE_DIR, 'google_categories.txt')
26
+
27
+ # Configuration for GLiNER integration
28
+ custom_spacy_config = {
29
+ "gliner_model": "urchade/gliner_small-v2.1",
30
+ "chunk_size": 128,
31
+ "labels": ["person", "organization", "location", "event", "work_of_art", "product", "service", "date", "number", "price", "address", "phone_number", "misc"],
32
+ "threshold": 0.5
33
+ }
34
+
35
+ # Model variables for lazy loading
36
+ nlp = None
37
+ sentence_model = None
38
+ google_categories = []
39
+
40
+ # Function to lazy load NLP model
41
+ def get_nlp():
42
+ global nlp
43
+ if nlp is None:
44
+ try:
45
+ nlp = spacy.blank("en")
46
+ nlp.add_pipe("gliner_spacy", config=custom_spacy_config)
47
+ except Exception as e:
48
+ raise
49
+ return nlp
50
+
51
+ # Function to lazy load sentence transformer model
52
+ def get_sentence_model():
53
+ global sentence_model
54
+ if sentence_model is None:
55
+ sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
56
+ return sentence_model
57
+
58
+ # Load Google's content categories
59
+ def load_google_categories():
60
+ global google_categories
61
+ if not google_categories:
62
+ try:
63
+ with open(CATEGORIES_FILE, 'r') as f:
64
+ google_categories = [line.strip() for line in f]
65
+ except Exception as e:
66
+ google_categories = []
67
+ return google_categories
68
+
69
+ # Function to perform NER using GLiNER with spaCy
70
+ def perform_ner(text):
71
+ try:
72
+ doc = get_nlp()(text)
73
+ return [(ent.text, ent.label_) for ent in doc.ents]
74
+ except Exception as e:
75
+ return []
76
+
77
+ # Function to extract entities using GLiNER with spaCy
78
+ def extract_entities(text):
79
+ try:
80
+ doc = get_nlp()(text)
81
+ entities = [(ent.text, ent.label_) for ent in doc.ents]
82
+ return entities if entities else ["No specific entities found"]
83
+ except Exception as e:
84
+ return ["Error extracting entities"]
85
+
86
+ # Function to precompute category embeddings
87
+ def compute_category_embeddings():
88
+ try:
89
+ categories = load_google_categories()
90
+ return get_sentence_model().encode(categories)
91
+ except Exception as e:
92
+ return []
93
+
94
+ # Function to perform topic modeling using sentence transformers
95
+ def perform_topic_modeling_from_similarities(similarities):
96
+ try:
97
+ categories = load_google_categories()
98
+ top_indices = similarities.argsort()[-3:][::-1]
99
+
100
+ best_match = categories[top_indices[0]]
101
+ second_best = categories[top_indices[1]]
102
+
103
+ if similarities[top_indices[0]] > similarities[top_indices[1]] * 1.1:
104
+ return best_match
105
+ else:
106
+ return f"{best_match} , {second_best}"
107
+ except Exception as e:
108
+ return "Error in topic modeling"
109
+
110
+ # Function to sort keywords by intent feature
111
+ def sort_by_keyword_feature(f):
112
+ if type(f) != str:
113
+ return "other"
114
+ f = f.lower()
115
+
116
+ informational_keywords = [
117
+ "advice", "help", "how do i", "how does", "how to", "ideas", "information", "tools", "list",
118
+ "resources", "tips", "tutorial", "diy", "ways to", "what does", "what is", "what was", "where are", "where does",
119
+ "where can", "where is", "where was", "when is", "when are", "when was", "where to", "who is", "who said", "who wrote",
120
+ "who are", "why are", "who was", "why is", "examples", "explained", "meaning of", "definition", "benefits of", "uses of",
121
+ "overview", "summary", "report", "study", "analysis", "research", "insight", "data", "facts", "details", "background",
122
+ "context", "news", "history", "documentation", "article", "paper", "blog", "forum", "discussion", "commentary",
123
+ "opinion", "perspective", "viewpoint", "guide", "difference between", "types of"
124
+ ]
125
+
126
+ navigational_keywords = [
127
+ "facebook", "meta", "twitter", "site", "login", "account", "official website", "homepage", "portal",
128
+ "signin", "register", "signup", "dashboard", "profile", "settings", "control panel", "main page",
129
+ "user area", "admin", "control", "access", "entry", "webpage", "navigate", "home", "site map",
130
+ "directory", "find", "search", "lookup", "index", "online", "internet", "web", "browser", "navigate to",
131
+ "goto", "landing page", "url", "hyperlink", "link", "web address", "navigate",
132
+ "web navigation", "website address", "app", "download", "status", "join"
133
+ ]
134
+
135
+ local_keywords = [
136
+ "closest", "close", "near me", "my area", "residential", "my zip", "my city", "nearby", "in town",
137
+ "around here", "local", "near", "vicinity", "local area", "nearest", "surrounding", "within miles",
138
+ "in my neighborhood", "district", "zone", "region", "near my location", "local services", "community",
139
+ "local shop", "in my vicinity", "local store", "suburb", "urban area", "within walking distance",
140
+ "around my place", "within my reach", "close by", "local office", "local branch", "near me now",
141
+ "in my locale", "within the city", "local market", "in my town", "local spot", "local point",
142
+ "local guide", "near my house", "local venue", "close to me", "within blocks", "local attractions",
143
+ "local events", "address"
144
+ ]
145
+
146
+ commercial_keywords = [
147
+ "best", "affordable", "budget", "cheap", "expensive", "review", "top", "service", "cost", "average cost",
148
+ "calculator", "provider", "company", "vs", "companies", "professional", "specialist", "compare",
149
+ "comparison", "rating", "testimonials", "recommendation", "advisor", "consultant", "expert", "ranking",
150
+ "leader", "top-rated", "best-selling", "trending", "featured", "highlighted", "recommended", "popular",
151
+ "favorite", "preferred", "choice", "most reviewed", "highest rated", "highly recommended", "award-winning",
152
+ "five-star", "customer favorite", "top pick", "critically acclaimed", "editor's choice", "people's choice",
153
+ "top performer", "best value", "best overall", "best quality", "best price", "most trusted", "leading brand",
154
+ "popular choice", "most popular", "fees", "pros and cons"
155
+ ]
156
+
157
+ transactional_keywords = [
158
+ "price", "quotes", "pricing", "purchase", "rates", "how much", "same day", "same-day", "buy", "order",
159
+ "discount", "deal", "offers", "sale", "checkout", "book", "reservation", "reserve", "bargain", "coupon",
160
+ "promo", "rebate", "clearance", "markdown", "buy one get one", "bogo", "special", "exclusive", "bundle",
161
+ "package", "subscription", "membership", "payment", "installment", "financing", "contract", "billing",
162
+ "invoice", "ticket", "admission", "entry", "enrollment", "register", "sign up", "pre-order", "e-commerce",
163
+ "shopping cart"
164
+ ]
165
+
166
+ if any(keyword in f for keyword in informational_keywords):
167
+ return "informational"
168
+ if any(keyword in f for keyword in navigational_keywords):
169
+ return "navigational"
170
+ if any(keyword in f for keyword in local_keywords):
171
+ return "local"
172
+ if any(keyword in f for keyword in commercial_keywords):
173
+ return "commercial investigation"
174
+ if any(keyword in f for keyword in transactional_keywords):
175
+ return "transactional"
176
+
177
+ return "other"
178
+
179
+ # Optimized batch processing of keywords
180
+ def batch_process_keywords(keywords, batch_size=8):
181
+ processed_data = {'Keywords': [], 'Intent': [], 'NER Entities': [], 'Google Content Topics': []}
182
+
183
+ try:
184
+ sentence_model = get_sentence_model()
185
+ category_embeddings = compute_category_embeddings()
186
+
187
+ for i in range(0, len(keywords), batch_size):
188
+ batch = keywords[i:i+batch_size]
189
+ batch_embeddings = sentence_model.encode(batch, batch_size=batch_size, show_progress_bar=False)
190
+
191
+ intents = [sort_by_keyword_feature(kw) for kw in batch]
192
+ entities = [extract_entities(kw) for kw in batch]
193
+
194
+ similarities = cosine_similarity(batch_embeddings, category_embeddings)
195
+ Google_Content_Topics = [perform_topic_modeling_from_similarities(sim) for sim in similarities]
196
+
197
+ processed_data['Keywords'].extend(batch)
198
+ processed_data['Intent'].extend(intents)
199
+
200
+ processed_entities = []
201
+ for entity_list in entities:
202
+ entity_strings = []
203
+ for entity in entity_list:
204
+ if isinstance(entity, tuple):
205
+ entity_strings.append(f"{entity[0]} ({entity[1]})")
206
+ else:
207
+ entity_strings.append(str(entity))
208
+ processed_entities.append(", ".join(entity_strings))
209
+
210
+ processed_data['NER Entities'].extend(processed_entities)
211
+ processed_data['Google Content Topics'].extend(Google_Content_Topics)
212
+
213
+ # Force garbage collection
214
+ gc.collect()
215
+
216
+ except Exception as e:
217
+ pass
218
+
219
+ return processed_data
220
+
221
+ # Main layout of the dashboard
222
+ app.layout = dbc.Container([
223
+ dcc.Store(id='models-loaded', data=False),
224
+ dbc.NavbarSimple(
225
+ children=[
226
+ dbc.NavItem(dbc.NavLink("About", href="#about", external_link=True)),
227
+ dbc.NavItem(dbc.NavLink("Contact", href="#contact", external_link=True)),
228
+ ],
229
+ brand="KeyIntentNER-T",
230
+ brand_href="https://github.com/jeredhiggins/KeyIntentNER-T",
231
+ color="#151515",
232
+ dark=True,
233
+ brand_style={"background": "linear-gradient(to right, #ff7e5f, #feb47b)", "-webkit-background-clip": "text", "color": "transparent", "textShadow": "0 0 1px #ffffff, 0 0 3px #ff7e5f, 0 0 5px #ff7e5f"},
234
+ ),
235
+
236
+ dbc.Row(dbc.Col(html.H1('Keyword Intent, Named Entity Recognition (NER), & Google Topic Modeling Dashboard', className='text-center text-light mb-4 mt-4'))),
237
+
238
+ dbc.Row([
239
+ dbc.Col([
240
+ dbc.Label('Enter keywords (one per line, maximum of 100):', className='text-light'),
241
+ dcc.Textarea(id='keyword-input', value='', style={'width': '100%', 'height': 100}),
242
+ dbc.Button('Submit', id='submit-button', color='primary', className='mb-3', disabled=True),
243
+ dbc.Alert(id='alert', is_open=False, duration=4000, color='danger', className='my-2'),
244
+ dbc.Alert(id='processing-alert', is_open=False, color='info', className='my-2'),
245
+ ], width=6)
246
+ ], justify='center'),
247
+
248
+ dbc.Row([
249
+ dbc.Col([
250
+ dcc.Loading(
251
+ id="loading",
252
+ type="default",
253
+ children=[html.Div(id="loading-output", className="my-4")]
254
+ ),
255
+ ], width=12)
256
+ ], justify='center', className="mb-4"),
257
+
258
+ dbc.Row(dbc.Col(dcc.Graph(id='bar-chart'), width=12)),
259
+
260
+ dbc.Row([
261
+ dbc.Col([
262
+ dbc.Label('View all keyword data for each intent category:', className='text-light mt-4'),
263
+ dcc.Dropdown(
264
+ id='table-intent-dropdown',
265
+ options=[],
266
+ placeholder='Select an Intent',
267
+ className='text-dark'
268
+ ),
269
+ ], width=6)
270
+ ], justify='center'),
271
+
272
+ dbc.Row(dbc.Col(
273
+ html.Div(id='keywords-table', style={'width': '100%'}),
274
+ width=12
275
+ )),
276
+
277
+ dbc.Row(dbc.Col(
278
+ dbc.Button('Download CSV For All Keywords', id='download-button', color='success', className='my-5', disabled=True),
279
+ width=12
280
+ ), justify='center'),
281
+
282
+ dcc.Download(id='download'),
283
+ dcc.Store(id='processed-data'),
284
+
285
+ # Explanation content
286
+ dbc.Row([
287
+ dbc.Col([
288
+ html.Div([
289
+ dbc.Card([
290
+ dbc.CardBody([
291
+ html.H3([html.I(className="fas fa-info-circle mr-2"), "About KeyIntentNER-T"], className="card-title text-warning"),
292
+ html.P("This tool provides valuable keyword insights for SEO and digital marketing professionals. Enter a list of keywords and get insights into Keyword Intent, NLP Entities extracted via NER (Named Entity Recognition), & Topics. I created KeyIntentNER-T as an example of how to use more modern NLP methods to gain insights into shorter text strings (keywords) and how this information may be understood by search engines using similar techniques.", className="card-text"),
293
+ ])
294
+ ], className="mb-4 shadow-sm"),
295
+ dbc.Row([
296
+ dbc.Col([
297
+ dbc.Card([
298
+ dbc.CardBody([
299
+ html.H3([html.I(className="fas fa-pen mr-2"), "Notes on the data"], className="card-title text-success"),
300
+ dbc.ListGroup([
301
+ dbc.ListGroupItem([html.I(className="fas fa-check mr-2"), "Keyword Intent is determined using a custom function that looks for the presence of specific terms and then classifies it into one of six predefined intent categories: 'informational', 'navigational', 'local', 'commercial investigation', 'transactional', or 'other'."]),
302
+ dbc.ListGroupItem([html.I(className="fas fa-check mr-2"), "NLP Entities are determined using GLiNER, an advanced Named Entity Recognition (NER) model that is better at classifying shorter text strings. Additionally, Entitites are mapped to all Entity Types included in the Google Cloud Natural Language API."]),
303
+ dbc.ListGroupItem([html.I(className="fas fa-check mr-2"), "Topics are determined by matching keywords to topics from Google's well-known Content and Product taxonomies."]),
304
+ dbc.ListGroupItem([html.I(className="fas fa-check mr-2"), "Since this tool is doing a lot behind the scenes, keyword processing can take anywhere from 30 seconds up to ~2 minutes."]),
305
+ ], flush=True)
306
+ ])
307
+ ], className="mb-4 shadow-sm")
308
+ ], md=6),
309
+ dbc.Col([
310
+ dbc.Card([
311
+ dbc.CardBody([
312
+ html.H3([html.I(className="fas fa-chart-line mr-2"), "Benefits for SEO"], className="card-title text-info"),
313
+ dbc.ListGroup([
314
+ dbc.ListGroupItem([html.I(className="fas fa-arrow-up mr-2"), "Improved content strategy by focusing your SEO efforts on creating more relevant/helpful content that addresses the search intent for keywords."]),
315
+ dbc.ListGroupItem([html.I(className="fas fa-bullseye mr-2"), "Enhanced keyword targeting by matching keywords to Google's well-known categories, ensuring your content is aligned with popular search themes."]),
316
+ dbc.ListGroupItem([html.I(className="fas fa-users mr-2"), "Better understanding of what kind of information a person is looking for."]),
317
+ dbc.ListGroupItem([html.I(className="fas fa-robot mr-2"), "Better understanding of how keywords can be interpreted by search engines."]),
318
+ ], flush=True)
319
+ ])
320
+ ], className="mb-4 shadow-sm")
321
+ ], md=6),
322
+ ]),
323
+ dbc.Card([
324
+ dbc.CardBody([
325
+ html.H3([html.I(className="fas fa-quote-left mr-2"), "GLiNER Model Citation"], className="card-title text-light"),
326
+ html.P([
327
+ "GLiNER: Generalist Model for Named Entity Recognition using Bidirectional Transformer. ",
328
+ html.Br(),
329
+ "Authors: Urchade Zaratiana, Nadi Tomeh, Pierre Holat, Thierry Charnois.",
330
+ html.Br(),
331
+ "Year: 2023.",
332
+ html.Br(),
333
+ html.A([html.I(className="fas fa-external-link-alt mr-2"), "arXiv:2311.08526"], href="https://arxiv.org/abs/2311.08526", target="_blank", className="btn btn-outline-warning btn-sm mt-2")
334
+ ], className="card-text"),
335
+ ])
336
+ ], className="mb-4 shadow-sm")
337
+ ], id="about")
338
+ ], width=12)
339
+ ], className="mt-5"),
340
+
341
+ # Contact section
342
+ dbc.Row([
343
+ dbc.Col([
344
+ html.Div([
345
+ dbc.Card([
346
+ dbc.CardBody([
347
+ html.H3([html.I(className="fas fa-envelope mr-2"), "Contact"], className="card-title text-info"),
348
+ html.P([
349
+ "For questions or if you are interested in building custom SEO dash apps, contact me at: ",
350
+ html.A("[email protected]", href="mailto:[email protected]", className="text-info")
351
+ ], className="card-text"),
352
+ ])
353
+ ], className="mb-4 shadow-sm")
354
+ ], id="contact")
355
+ ], width=12)
356
+ ], className="mt-4 mb-4"),
357
+
358
+ # JS for smooth scrolling
359
+ html.Div([
360
+ html.Script('''
361
+ document.addEventListener("DOMContentLoaded", function() {
362
+ var links = document.querySelectorAll("a[href^='#']");
363
+ links.forEach(function(link) {
364
+ link.addEventListener("click", function(e) {
365
+ e.preventDefault();
366
+ var targetId = this.getAttribute("href").substring(1);
367
+ var targetElement = document.getElementById(targetId);
368
+ if (targetElement) {
369
+ targetElement.scrollIntoView({
370
+ behavior: "smooth",
371
+ block: "start"
372
+ });
373
+ }
374
+ });
375
+ });
376
+ });
377
+ ''')
378
+ ]),
379
+
380
+ ], fluid=True)
381
+
382
+ # Combined callback
383
+ @app.callback(
384
+ [Output('models-loaded', 'data'),
385
+ Output('submit-button', 'disabled'),
386
+ Output('alert', 'is_open'),
387
+ Output('alert', 'children'),
388
+ Output('alert', 'color'),
389
+ Output('processed-data', 'data'),
390
+ Output('loading-output', 'children'),
391
+ Output('processing-alert', 'is_open'),
392
+ Output('processing-alert', 'children')],
393
+ [Input('models-loaded', 'data'),
394
+ Input('submit-button', 'n_clicks')],
395
+ [State('keyword-input', 'value')]
396
+ )
397
+ def combined_callback(loaded, n_clicks, keyword_input):
398
+ ctx = callback_context
399
+ triggered_id = ctx.triggered[0]['prop_id'].split('.')[0]
400
+
401
+ if triggered_id == 'models-loaded':
402
+ return handle_model_loading(loaded)
403
+ elif triggered_id == 'submit-button':
404
+ return handle_keyword_processing(n_clicks, keyword_input)
405
+ else:
406
+ # Default return values
407
+ return loaded, False, False, "", "success", None, '', False, ''
408
+
409
+ def handle_model_loading(loaded):
410
+ if not loaded:
411
+ try:
412
+ # Lazy loading will occur when models are first used
413
+ return True, False, True, "Models ready to load", "success", None, '', False, ''
414
+ except Exception as e:
415
+ return False, True, True, f"Error preparing models: {str(e)}", "danger", None, '', False, ''
416
+ return loaded, not loaded, False, "", "success", None, '', False, ''
417
+
418
+ def handle_keyword_processing(n_clicks, keyword_input):
419
+ if n_clicks is None or not keyword_input:
420
+ return True, False, False, "", "success", None, '', False, ''
421
+
422
+ keywords = [kw.strip() for kw in keyword_input.split('\n')[:100] if kw.strip()]
423
+ processed_data = batch_process_keywords(keywords)
424
+
425
+ return True, False, False, "", "success", processed_data, '', True, "Keyword processing complete!"
426
+
427
+ # Callback for updating the bar chart
428
+ @app.callback(
429
+ Output('bar-chart', 'figure'),
430
+ [Input('processed-data', 'data')]
431
+ )
432
+ def update_bar_chart(processed_data):
433
+ if processed_data is None:
434
+ return {
435
+ 'data': [],
436
+ 'layout': {
437
+ 'height': 0,
438
+ 'annotations': [{
439
+ 'text': '',
440
+ 'xref': 'paper',
441
+ 'yref': 'paper',
442
+ 'showarrow': False,
443
+ 'font': {'size': 28}
444
+ }]
445
+ }
446
+ }
447
+
448
+ df = pd.DataFrame(processed_data)
449
+ intent_counts = df['Intent'].value_counts().reset_index()
450
+ intent_counts.columns = ['Intent', 'Count']
451
+
452
+ fig = px.bar(intent_counts, x='Intent', y='Count', color='Intent',
453
+ title='Keyword Intent Distribution',
454
+ color_discrete_sequence=px.colors.qualitative.Dark2)
455
+
456
+ fig.update_layout(
457
+ plot_bgcolor='#222222',
458
+ paper_bgcolor='#222222',
459
+ font_color='white',
460
+ height=400,
461
+ legend=dict(
462
+ orientation="h",
463
+ yanchor="bottom",
464
+ y=1.02,
465
+ xanchor="right",
466
+ x=1
467
+ )
468
+ )
469
+
470
+ return fig
471
+
472
+ # Callback for updating the dropdown and download button
473
+ @app.callback(
474
+ [Output('table-intent-dropdown', 'options'),
475
+ Output('download-button', 'disabled')],
476
+ [Input('processed-data', 'data')]
477
+ )
478
+ def update_dropdown_and_button(processed_data):
479
+ if processed_data is None:
480
+ return [], True
481
+
482
+ df = pd.DataFrame(processed_data)
483
+ intents = df['Intent'].unique()
484
+ options = [{'label': intent, 'value': intent} for intent in intents]
485
+ return options, False
486
+
487
+ # Callback for updating the keywords table
488
+ @app.callback(
489
+ Output('keywords-table', 'children'),
490
+ [Input('table-intent-dropdown', 'value')],
491
+ [State('processed-data', 'data')]
492
+ )
493
+ def update_keywords_table(selected_intent, processed_data):
494
+ if processed_data is None or selected_intent is None:
495
+ return html.Div()
496
+
497
+ df = pd.DataFrame(processed_data)
498
+ filtered_df = df[df['Intent'] == selected_intent]
499
+
500
+ table = DataTable(
501
+ columns=[{"name": i, "id": i} for i in filtered_df.columns],
502
+ data=filtered_df.to_dict('records'),
503
+ style_table={'overflowX': 'auto'},
504
+ style_cell={'textAlign': 'left', 'whiteSpace': 'normal', 'height': 'auto', 'minWidth': '100px', 'width': '100px', 'maxWidth': '100px'},
505
+ style_header={'backgroundColor': 'rgb(30, 30, 30)', 'color': 'white'},
506
+ style_data={'backgroundColor': 'rgb(50, 50, 50)', 'color': 'white'},
507
+ sort_action='native',
508
+ page_action='native',
509
+ page_current=0
510
+ )
511
+ return table
512
+
513
+ # Callback for downloading CSV
514
+ @app.callback(
515
+ Output('download', 'data'),
516
+ [Input('download-button', 'n_clicks')],
517
+ [State('processed-data', 'data')]
518
+ )
519
+ def download_csv(n_clicks, processed_data):
520
+ if n_clicks is None or processed_data is None:
521
+ return None
522
+
523
+ df = pd.DataFrame(processed_data)
524
+ csv_string = df.to_csv(index=False, encoding='utf-8')
525
+ return dict(content=csv_string, filename="KeyIntentNER-T_keyword_analysis.csv")
526
+
527
+ # Modified the server run command for HuggingFace Spaces
528
+ if __name__ == "__main__":
529
+ app.run_server(debug=False, host="0.0.0.0", port=7860)
google_categories.txt ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ dash
2
+ dash-bootstrap-components
3
+ pandas
4
+ plotly
5
+ spacy
6
+ sentence-transformers
7
+ scikit-learn
8
+ gliner-spacy
9
+ gunicorn