Upload 9 files
Browse files- LICENSE +201 -0
- README.md +2 -4
- config.py +53 -0
- generator.py +286 -0
- main.py +52 -0
- post_processor.py +113 -0
- processor.py +120 -0
- requirements.txt +24 -0
- scraper.py +103 -0
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.
|
README.md
CHANGED
|
@@ -1,4 +1,2 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
---
|
| 4 |
-
hi
|
|
|
|
| 1 |
+
# bloomington-guide
|
| 2 |
+
The repository consists of the code for creation of the dataset and training the small language models via model distillation.
|
|
|
|
|
|
config.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
# API Keys
|
| 5 |
+
SERP_API_KEY = "2d78ac7b2491065a206825e614a2f20e6f70f90a7958463883f58ae2c2f55bae"
|
| 6 |
+
GEMINI_API_KEY = "AIzaSyAPf9oyyb0l9vQcP46Yh1SkG1dE8GvJJv0"
|
| 7 |
+
|
| 8 |
+
# API Limits
|
| 9 |
+
SERP_MONTHLY_LIMIT = 80
|
| 10 |
+
GEMINI_RATE_LIMIT = 10 # requests per minute
|
| 11 |
+
PAIRS_PER_PROMPT = 5
|
| 12 |
+
TARGET_QA_PAIRS = 1000
|
| 13 |
+
|
| 14 |
+
# Project Paths
|
| 15 |
+
PROJECT_ROOT = Path(__file__).parent
|
| 16 |
+
DATA_DIR = PROJECT_ROOT / "data"
|
| 17 |
+
RAW_DIR = DATA_DIR / "raw"
|
| 18 |
+
PROCESSED_DIR = DATA_DIR / "processed"
|
| 19 |
+
FINAL_DIR = DATA_DIR / "final"
|
| 20 |
+
LOG_DIR = PROJECT_ROOT / "logs"
|
| 21 |
+
|
| 22 |
+
# Create directories if they don't exist
|
| 23 |
+
for dir_path in [DATA_DIR, RAW_DIR, PROCESSED_DIR, FINAL_DIR, LOG_DIR]:
|
| 24 |
+
dir_path.mkdir(parents=True, exist_ok=True)
|
| 25 |
+
|
| 26 |
+
# Search Queries
|
| 27 |
+
SEARCH_QUERIES = {
|
| 28 |
+
"attractions": [
|
| 29 |
+
"Bloomington Indiana tourist attractions",
|
| 30 |
+
"Indiana University landmarks",
|
| 31 |
+
"Bloomington cultural venues"
|
| 32 |
+
],
|
| 33 |
+
"dining": [
|
| 34 |
+
"Best restaurants Bloomington Indiana",
|
| 35 |
+
"Bloomington cafes and bars",
|
| 36 |
+
"Food trucks Bloomington IN"
|
| 37 |
+
],
|
| 38 |
+
"events": [
|
| 39 |
+
"Events in Bloomington Indiana",
|
| 40 |
+
"Festivals Bloomington IN",
|
| 41 |
+
"Concerts Bloomington Indiana"
|
| 42 |
+
],
|
| 43 |
+
"outdoor": [
|
| 44 |
+
"Bloomington parks and recreation",
|
| 45 |
+
"Hiking trails Bloomington IN",
|
| 46 |
+
"Lake Monroe activities"
|
| 47 |
+
],
|
| 48 |
+
"accommodation": [
|
| 49 |
+
"Hotels Bloomington Indiana",
|
| 50 |
+
"B&B Bloomington IN",
|
| 51 |
+
"Student housing IU Bloomington"
|
| 52 |
+
]
|
| 53 |
+
}
|
generator.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import time
|
| 3 |
+
import logging
|
| 4 |
+
import re
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from typing import Dict, List, Tuple
|
| 7 |
+
import google.generativeai as genai
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
from config import (
|
| 12 |
+
GEMINI_API_KEY, GEMINI_RATE_LIMIT, PAIRS_PER_PROMPT,
|
| 13 |
+
TARGET_QA_PAIRS, PROCESSED_DIR, FINAL_DIR, LOG_DIR
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
class QAPairGenerator:
|
| 17 |
+
def __init__(self):
|
| 18 |
+
# Configure Gemini
|
| 19 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 20 |
+
self.model = genai.GenerativeModel('gemini-1.5-flash')
|
| 21 |
+
|
| 22 |
+
# Set up logging
|
| 23 |
+
log_file = LOG_DIR / f"generator_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
|
| 24 |
+
logging.basicConfig(
|
| 25 |
+
level=logging.INFO,
|
| 26 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 27 |
+
filename=log_file
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
self.generated_pairs = []
|
| 31 |
+
self.failed_generations = []
|
| 32 |
+
self.total_pairs_generated = 0 # Add counter for total pairs
|
| 33 |
+
|
| 34 |
+
def _generate_qa_batch(self, content: str, category: str) -> List[Dict]:
|
| 35 |
+
"""Generate a batch of QA pairs from content using regex parsing"""
|
| 36 |
+
prompt = f"""
|
| 37 |
+
Based on the following content about Bloomington, Indiana, generate {PAIRS_PER_PROMPT} different instruction-response pairs.
|
| 38 |
+
The content is related to the category: {category}
|
| 39 |
+
|
| 40 |
+
Focus on creating specific, practical questions that tourists might ask, with detailed, actionable responses.
|
| 41 |
+
Include relevant details like operating hours, costs, locations, and tips when applicable.
|
| 42 |
+
|
| 43 |
+
Format your response EXACTLY as a JSON array with each object containing "instruction", "response", and "category" fields.
|
| 44 |
+
|
| 45 |
+
Example format:
|
| 46 |
+
[
|
| 47 |
+
{{
|
| 48 |
+
"instruction": "What are the peak times to visit the Sample Gardens and how much does it cost?",
|
| 49 |
+
"response": "Sample Gardens is busiest during weekends and holidays. Admission is $10 for adults, $5 for children (5-12), and free for children under 5. To avoid crowds, visit on weekday mornings between 9-11am. Free parking is available.",
|
| 50 |
+
"category": "attractions"
|
| 51 |
+
}}
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
Content: {content}
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
response = self.model.generate_content(prompt)
|
| 59 |
+
response_text = response.text.strip()
|
| 60 |
+
|
| 61 |
+
# Try regex parsing first
|
| 62 |
+
try:
|
| 63 |
+
# Pattern to match the entire JSON array
|
| 64 |
+
array_pattern = r'\[\s*(\{[^]]*\})\s*(?:,\s*(\{[^]]*\})\s*)*\]'
|
| 65 |
+
array_match = re.search(array_pattern, response_text, re.DOTALL)
|
| 66 |
+
|
| 67 |
+
if array_match:
|
| 68 |
+
json_str = array_match.group(0)
|
| 69 |
+
|
| 70 |
+
# Additional regex to validate individual objects
|
| 71 |
+
object_pattern = r'\{\s*"instruction":\s*"([^"]*)",\s*"response":\s*"([^"]*)",\s*"category":\s*"([^"]*)"\s*\}'
|
| 72 |
+
objects = re.finditer(object_pattern, json_str)
|
| 73 |
+
|
| 74 |
+
valid_pairs = []
|
| 75 |
+
for obj_match in objects:
|
| 76 |
+
instruction = obj_match.group(1)
|
| 77 |
+
response = obj_match.group(2)
|
| 78 |
+
obj_category = obj_match.group(3)
|
| 79 |
+
|
| 80 |
+
# Validate lengths
|
| 81 |
+
if len(instruction) >= 20 and len(response) >= 50:
|
| 82 |
+
valid_pairs.append({
|
| 83 |
+
'instruction': instruction,
|
| 84 |
+
'response': response,
|
| 85 |
+
'category': category # Use the passed category instead of the one in response
|
| 86 |
+
})
|
| 87 |
+
else:
|
| 88 |
+
logging.warning(f"Pair rejected due to length requirements: Q: {len(instruction)} chars, A: {len(response)} chars")
|
| 89 |
+
|
| 90 |
+
if valid_pairs:
|
| 91 |
+
return valid_pairs
|
| 92 |
+
|
| 93 |
+
logging.warning("Regex parsing failed, attempting JSON parsing as fallback")
|
| 94 |
+
|
| 95 |
+
except Exception as regex_error:
|
| 96 |
+
logging.warning(f"Regex parsing error: {str(regex_error)}")
|
| 97 |
+
|
| 98 |
+
# Fallback to JSON parsing
|
| 99 |
+
try:
|
| 100 |
+
# Find the first '[' and last ']' to extract JSON array
|
| 101 |
+
start_idx = response_text.find('[')
|
| 102 |
+
end_idx = response_text.rfind(']') + 1
|
| 103 |
+
|
| 104 |
+
if start_idx != -1 and end_idx > start_idx:
|
| 105 |
+
json_str = response_text[start_idx:end_idx]
|
| 106 |
+
pairs = json.loads(json_str)
|
| 107 |
+
else:
|
| 108 |
+
pairs = json.loads(response_text)
|
| 109 |
+
|
| 110 |
+
# Validate pairs
|
| 111 |
+
valid_pairs = []
|
| 112 |
+
for pair in pairs:
|
| 113 |
+
if (isinstance(pair, dict) and
|
| 114 |
+
'instruction' in pair and
|
| 115 |
+
'response' in pair and
|
| 116 |
+
isinstance(pair['instruction'], str) and
|
| 117 |
+
isinstance(pair['response'], str) and
|
| 118 |
+
len(pair['instruction']) >= 20 and
|
| 119 |
+
len(pair['response']) >= 50):
|
| 120 |
+
|
| 121 |
+
pair['category'] = category
|
| 122 |
+
valid_pairs.append(pair)
|
| 123 |
+
else:
|
| 124 |
+
logging.warning(f"Invalid pair structure or length: {pair}")
|
| 125 |
+
|
| 126 |
+
return valid_pairs
|
| 127 |
+
|
| 128 |
+
except json.JSONDecodeError as json_error:
|
| 129 |
+
logging.error(f"JSON parsing error: {str(json_error)}\nResponse text: {response_text}")
|
| 130 |
+
return []
|
| 131 |
+
|
| 132 |
+
except Exception as e:
|
| 133 |
+
logging.error(f"Error in QA pair generation: {str(e)}")
|
| 134 |
+
self.failed_generations.append({
|
| 135 |
+
'content': content,
|
| 136 |
+
'category': category,
|
| 137 |
+
'error': str(e),
|
| 138 |
+
'response_text': response_text if 'response_text' in locals() else None,
|
| 139 |
+
'timestamp': datetime.now().isoformat()
|
| 140 |
+
})
|
| 141 |
+
return []
|
| 142 |
+
|
| 143 |
+
def generate_pairs_for_category(self, category: str) -> List[Dict]:
|
| 144 |
+
"""Generate QA pairs for a specific category"""
|
| 145 |
+
input_file = PROCESSED_DIR / f"{category}_processed.json"
|
| 146 |
+
|
| 147 |
+
try:
|
| 148 |
+
with open(input_file, 'r') as f:
|
| 149 |
+
processed_data = json.load(f)
|
| 150 |
+
except Exception as e:
|
| 151 |
+
logging.error(f"Error loading {input_file}: {e}")
|
| 152 |
+
return []
|
| 153 |
+
|
| 154 |
+
category_pairs = []
|
| 155 |
+
|
| 156 |
+
# Calculate remaining pairs needed
|
| 157 |
+
remaining_pairs = TARGET_QA_PAIRS - self.total_pairs_generated
|
| 158 |
+
|
| 159 |
+
if remaining_pairs <= 0:
|
| 160 |
+
logging.info("Target number of QA pairs reached")
|
| 161 |
+
return []
|
| 162 |
+
|
| 163 |
+
for item in tqdm(processed_data, desc=f"Generating pairs for {category}"):
|
| 164 |
+
if self.total_pairs_generated >= TARGET_QA_PAIRS:
|
| 165 |
+
logging.info(f"Target of {TARGET_QA_PAIRS} pairs reached. Stopping generation.")
|
| 166 |
+
break
|
| 167 |
+
|
| 168 |
+
# Combine all available content
|
| 169 |
+
content = f"{item['title']} {item['snippet']}"
|
| 170 |
+
if 'additional_content' in item:
|
| 171 |
+
content += f" {item['additional_content']}"
|
| 172 |
+
|
| 173 |
+
pairs = self._generate_qa_batch(content, category)
|
| 174 |
+
|
| 175 |
+
# Only take as many pairs as needed
|
| 176 |
+
pairs_needed = min(len(pairs), TARGET_QA_PAIRS - self.total_pairs_generated)
|
| 177 |
+
valid_pairs = pairs[:pairs_needed]
|
| 178 |
+
|
| 179 |
+
category_pairs.extend(valid_pairs)
|
| 180 |
+
self.total_pairs_generated += len(valid_pairs)
|
| 181 |
+
|
| 182 |
+
logging.info(f"Progress: {self.total_pairs_generated}/{TARGET_QA_PAIRS} pairs")
|
| 183 |
+
|
| 184 |
+
if self.total_pairs_generated >= TARGET_QA_PAIRS:
|
| 185 |
+
break
|
| 186 |
+
|
| 187 |
+
time.sleep(60/GEMINI_RATE_LIMIT) # Respect rate limit
|
| 188 |
+
|
| 189 |
+
# Save category pairs
|
| 190 |
+
output_file = FINAL_DIR / f"{category}_qa_pairs.json"
|
| 191 |
+
with open(output_file, 'w') as f:
|
| 192 |
+
json.dump(category_pairs, f, indent=2)
|
| 193 |
+
|
| 194 |
+
return category_pairs
|
| 195 |
+
|
| 196 |
+
def generate_all_pairs(self) -> None:
|
| 197 |
+
"""Generate QA pairs for all categories until target is reached"""
|
| 198 |
+
categories = [f.stem.replace('_processed', '')
|
| 199 |
+
for f in PROCESSED_DIR.glob('*_processed.json')]
|
| 200 |
+
|
| 201 |
+
all_pairs = []
|
| 202 |
+
|
| 203 |
+
# Keep generating pairs until we reach the target
|
| 204 |
+
while self.total_pairs_generated < TARGET_QA_PAIRS and categories:
|
| 205 |
+
for category in categories[:]: # Create a copy to modify safely
|
| 206 |
+
if self.total_pairs_generated >= TARGET_QA_PAIRS:
|
| 207 |
+
break
|
| 208 |
+
|
| 209 |
+
logging.info(f"Starting generation for category: {category}")
|
| 210 |
+
category_pairs = self.generate_pairs_for_category(category)
|
| 211 |
+
|
| 212 |
+
if not category_pairs: # If no more pairs can be generated for this category
|
| 213 |
+
categories.remove(category)
|
| 214 |
+
continue
|
| 215 |
+
|
| 216 |
+
all_pairs.extend(category_pairs)
|
| 217 |
+
logging.info(f"Generated {len(category_pairs)} pairs for {category}")
|
| 218 |
+
self._save_progress(all_pairs)
|
| 219 |
+
|
| 220 |
+
if self.total_pairs_generated >= TARGET_QA_PAIRS:
|
| 221 |
+
break
|
| 222 |
+
|
| 223 |
+
# Check if we need to continue
|
| 224 |
+
if self.total_pairs_generated < TARGET_QA_PAIRS and not categories:
|
| 225 |
+
logging.warning(f"Exhausted all categories. Generated {self.total_pairs_generated}/{TARGET_QA_PAIRS} pairs")
|
| 226 |
+
break
|
| 227 |
+
|
| 228 |
+
# Save final results
|
| 229 |
+
self._save_final_results(all_pairs)
|
| 230 |
+
|
| 231 |
+
def _save_progress(self, pairs: List[Dict]) -> None:
|
| 232 |
+
"""Save intermediate progress"""
|
| 233 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 234 |
+
progress_file = FINAL_DIR / f"qa_pairs_progress_{timestamp}.json"
|
| 235 |
+
|
| 236 |
+
progress_data = {
|
| 237 |
+
'pairs': pairs,
|
| 238 |
+
'stats': {
|
| 239 |
+
'total_pairs': len(pairs),
|
| 240 |
+
'target_pairs': TARGET_QA_PAIRS,
|
| 241 |
+
'completion_percentage': (self.total_pairs_generated / TARGET_QA_PAIRS) * 100,
|
| 242 |
+
'pairs_per_category': pd.DataFrame(pairs)['category'].value_counts().to_dict(),
|
| 243 |
+
'timestamp': timestamp
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
with open(progress_file, 'w') as f:
|
| 248 |
+
json.dump(progress_data, f, indent=2)
|
| 249 |
+
|
| 250 |
+
def _save_final_results(self, pairs: List[Dict]) -> None:
|
| 251 |
+
"""Save final results and statistics"""
|
| 252 |
+
final_file = FINAL_DIR / "final_qa_pairs.json"
|
| 253 |
+
|
| 254 |
+
final_data = {
|
| 255 |
+
'pairs': pairs,
|
| 256 |
+
'stats': {
|
| 257 |
+
'total_pairs_generated': self.total_pairs_generated,
|
| 258 |
+
'target_pairs': TARGET_QA_PAIRS,
|
| 259 |
+
'completion_percentage': (self.total_pairs_generated / TARGET_QA_PAIRS) * 100,
|
| 260 |
+
'pairs_per_category': pd.DataFrame(pairs)['category'].value_counts().to_dict(),
|
| 261 |
+
'avg_instruction_length': pd.DataFrame(pairs)['instruction'].str.len().mean(),
|
| 262 |
+
'avg_response_length': pd.DataFrame(pairs)['response'].str.len().mean(),
|
| 263 |
+
'failed_generations': len(self.failed_generations),
|
| 264 |
+
'completion_timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 265 |
+
}
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
# Save main results
|
| 269 |
+
with open(final_file, 'w') as f:
|
| 270 |
+
json.dump(final_data, f, indent=2)
|
| 271 |
+
|
| 272 |
+
# Save as CSV
|
| 273 |
+
df = pd.DataFrame(pairs)
|
| 274 |
+
df.to_csv(FINAL_DIR / "final_qa_pairs.csv", index=False)
|
| 275 |
+
|
| 276 |
+
# Save failed generations for analysis
|
| 277 |
+
if self.failed_generations:
|
| 278 |
+
with open(FINAL_DIR / "failed_generations.json", 'w') as f:
|
| 279 |
+
json.dump(self.failed_generations, f, indent=2)
|
| 280 |
+
|
| 281 |
+
logging.info(f"""
|
| 282 |
+
Generation completed:
|
| 283 |
+
- Total pairs generated: {self.total_pairs_generated}
|
| 284 |
+
- Target pairs: {TARGET_QA_PAIRS}
|
| 285 |
+
- Categories used: {len(set(pair['category'] for pair in pairs))}
|
| 286 |
+
""")
|
main.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
|
| 4 |
+
from scraper import BloomingtonScraper
|
| 5 |
+
from processor import DataProcessor
|
| 6 |
+
from generator import QAPairGenerator
|
| 7 |
+
from config import LOG_DIR
|
| 8 |
+
|
| 9 |
+
def setup_logging() -> None:
|
| 10 |
+
"""Set up logging configuration"""
|
| 11 |
+
log_file = LOG_DIR / f"main_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
|
| 12 |
+
logging.basicConfig(
|
| 13 |
+
level=logging.INFO,
|
| 14 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 15 |
+
handlers=[
|
| 16 |
+
logging.FileHandler(log_file),
|
| 17 |
+
logging.StreamHandler() # Also print to console
|
| 18 |
+
]
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
def main():
|
| 22 |
+
setup_logging()
|
| 23 |
+
logging.info("Starting Bloomington Tourist Guide data collection and QA pair generation")
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
# Step 1: Data Collection
|
| 27 |
+
logging.info("Starting data collection...")
|
| 28 |
+
scraper = BloomingtonScraper()
|
| 29 |
+
scraper.scrape_all_categories()
|
| 30 |
+
search_stats = scraper.get_search_stats()
|
| 31 |
+
logging.info(f"Data collection completed. Search stats: {search_stats}")
|
| 32 |
+
|
| 33 |
+
# Step 2: Data Processing
|
| 34 |
+
logging.info("Starting data processing...")
|
| 35 |
+
processor = DataProcessor()
|
| 36 |
+
processor.process_all_categories()
|
| 37 |
+
logging.info("Data processing completed")
|
| 38 |
+
|
| 39 |
+
# Step 3: QA Pair Generation
|
| 40 |
+
logging.info("Starting QA pair generation...")
|
| 41 |
+
generator = QAPairGenerator()
|
| 42 |
+
generator.generate_all_pairs()
|
| 43 |
+
logging.info("QA pair generation completed")
|
| 44 |
+
|
| 45 |
+
except Exception as e:
|
| 46 |
+
logging.error(f"Error in main execution: {e}", exc_info=True)
|
| 47 |
+
raise
|
| 48 |
+
|
| 49 |
+
logging.info("Pipeline completed successfully")
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
main()
|
post_processor.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import List, Dict
|
| 5 |
+
import logging
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
class DatasetConverter:
|
| 9 |
+
def __init__(self, input_file: str, output_dir: str):
|
| 10 |
+
"""
|
| 11 |
+
Initialize the converter with input and output paths
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
input_file (str): Path to the input JSON file
|
| 15 |
+
output_dir (str): Directory to save the output files
|
| 16 |
+
"""
|
| 17 |
+
self.input_file = Path(input_file)
|
| 18 |
+
self.output_dir = Path(output_dir)
|
| 19 |
+
self.output_dir.mkdir(parents=True, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
# Set up logging
|
| 22 |
+
logging.basicConfig(
|
| 23 |
+
level=logging.INFO,
|
| 24 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def _format_message(self, instruction: str, response: str) -> List[Dict]:
|
| 28 |
+
"""
|
| 29 |
+
Format a single instruction-response pair into the required message format
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
instruction (str): The user instruction/question
|
| 33 |
+
response (str): The assistant's response
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
List[Dict]: Formatted message list
|
| 37 |
+
"""
|
| 38 |
+
return [
|
| 39 |
+
{"content": instruction, "role": "user"},
|
| 40 |
+
{"content": response, "role": "assistant"}
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
def convert(self) -> None:
|
| 44 |
+
"""
|
| 45 |
+
Convert the input JSON file to HuggingFace dataset format
|
| 46 |
+
"""
|
| 47 |
+
try:
|
| 48 |
+
# Read input JSON file
|
| 49 |
+
logging.info(f"Reading input file: {self.input_file}")
|
| 50 |
+
with open(self.input_file, 'r', encoding='utf-8') as f:
|
| 51 |
+
data = json.load(f)
|
| 52 |
+
|
| 53 |
+
# Extract QA pairs from the JSON structure
|
| 54 |
+
qa_pairs = data.get('pairs', []) # Handle both raw list and nested structure
|
| 55 |
+
if not qa_pairs and isinstance(data, list):
|
| 56 |
+
qa_pairs = data
|
| 57 |
+
|
| 58 |
+
logging.info(f"Found {len(qa_pairs)} QA pairs")
|
| 59 |
+
|
| 60 |
+
# Create dataset records
|
| 61 |
+
dataset_records = []
|
| 62 |
+
for idx, pair in enumerate(qa_pairs):
|
| 63 |
+
try:
|
| 64 |
+
messages = self._format_message(
|
| 65 |
+
pair['instruction'],
|
| 66 |
+
pair['response']
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
dataset_records.append({
|
| 70 |
+
'id': f'bloomington_{idx:05d}',
|
| 71 |
+
'messages': messages
|
| 72 |
+
})
|
| 73 |
+
except KeyError as e:
|
| 74 |
+
logging.warning(f"Skipping invalid pair at index {idx}: {e}")
|
| 75 |
+
|
| 76 |
+
# Convert to DataFrame
|
| 77 |
+
df = pd.DataFrame(dataset_records)
|
| 78 |
+
|
| 79 |
+
# Save as CSV and JSON
|
| 80 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 81 |
+
csv_path = self.output_dir / f'bloomington_dataset_{timestamp}.csv'
|
| 82 |
+
json_path = self.output_dir / f'bloomington_dataset_{timestamp}.json'
|
| 83 |
+
|
| 84 |
+
df.to_csv(csv_path, index=False)
|
| 85 |
+
df.to_json(json_path, orient='records', indent=2)
|
| 86 |
+
|
| 87 |
+
logging.info(f"Successfully converted {len(dataset_records)} records")
|
| 88 |
+
logging.info(f"Saved dataset to:\n- CSV: {csv_path}\n- JSON: {json_path}")
|
| 89 |
+
|
| 90 |
+
# Generate and save dataset statistics
|
| 91 |
+
stats = {
|
| 92 |
+
'total_records': len(dataset_records),
|
| 93 |
+
'avg_instruction_length': sum(len(record['messages'][0]['content'])
|
| 94 |
+
for record in dataset_records) / len(dataset_records),
|
| 95 |
+
'avg_response_length': sum(len(record['messages'][1]['content'])
|
| 96 |
+
for record in dataset_records) / len(dataset_records),
|
| 97 |
+
'timestamp': timestamp
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
with open(self.output_dir / f'dataset_stats_{timestamp}.json', 'w') as f:
|
| 101 |
+
json.dump(stats, f, indent=2)
|
| 102 |
+
|
| 103 |
+
except Exception as e:
|
| 104 |
+
logging.error(f"Error converting dataset: {e}", exc_info=True)
|
| 105 |
+
raise
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
# Example usage
|
| 109 |
+
converter = DatasetConverter(
|
| 110 |
+
input_file="data/final/final_qa_pairs.json",
|
| 111 |
+
output_dir="data/huggingface"
|
| 112 |
+
)
|
| 113 |
+
converter.convert()
|
processor.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from typing import Dict, List
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from bs4 import BeautifulSoup
|
| 7 |
+
import requests
|
| 8 |
+
from urllib.parse import urlparse
|
| 9 |
+
|
| 10 |
+
from config import RAW_DIR, PROCESSED_DIR, LOG_DIR
|
| 11 |
+
|
| 12 |
+
class DataProcessor:
|
| 13 |
+
def __init__(self):
|
| 14 |
+
# Set up logging
|
| 15 |
+
log_file = LOG_DIR / f"processor_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
|
| 16 |
+
logging.basicConfig(
|
| 17 |
+
level=logging.INFO,
|
| 18 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 19 |
+
filename=log_file
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
self.processed_data = {}
|
| 23 |
+
|
| 24 |
+
def _extract_domain(self, url: str) -> str:
|
| 25 |
+
"""Extract domain from URL"""
|
| 26 |
+
try:
|
| 27 |
+
return urlparse(url).netloc
|
| 28 |
+
except Exception:
|
| 29 |
+
return ""
|
| 30 |
+
|
| 31 |
+
def _scrape_webpage(self, url: str) -> str:
|
| 32 |
+
"""Scrape additional content from webpage"""
|
| 33 |
+
try:
|
| 34 |
+
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
|
| 35 |
+
response = requests.get(url, headers=headers, timeout=10)
|
| 36 |
+
soup = BeautifulSoup(response.text, 'lxml')
|
| 37 |
+
|
| 38 |
+
# Remove unwanted elements
|
| 39 |
+
for element in soup(['script', 'style', 'nav', 'footer']):
|
| 40 |
+
element.decompose()
|
| 41 |
+
|
| 42 |
+
return ' '.join(soup.stripped_strings)
|
| 43 |
+
except Exception as e:
|
| 44 |
+
logging.error(f"Error scraping {url}: {e}")
|
| 45 |
+
return ""
|
| 46 |
+
|
| 47 |
+
def process_category(self, category: str) -> List[Dict]:
|
| 48 |
+
"""Process data for a single category"""
|
| 49 |
+
input_file = RAW_DIR / f"{category}_results.json"
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
with open(input_file, 'r') as f:
|
| 53 |
+
raw_results = json.load(f)
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logging.error(f"Error loading {input_file}: {e}")
|
| 56 |
+
return []
|
| 57 |
+
|
| 58 |
+
processed_results = []
|
| 59 |
+
|
| 60 |
+
for result in raw_results:
|
| 61 |
+
processed_result = {
|
| 62 |
+
'title': result.get('title', ''),
|
| 63 |
+
'snippet': result.get('snippet', ''),
|
| 64 |
+
'url': result.get('link', ''),
|
| 65 |
+
'domain': self._extract_domain(result.get('link', '')),
|
| 66 |
+
'category': category
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
# Add additional content for certain domains
|
| 70 |
+
if any(domain in processed_result['domain']
|
| 71 |
+
for domain in ['visitbloomington.com', 'indiana.edu', 'bloomington.in.gov']):
|
| 72 |
+
additional_content = self._scrape_webpage(processed_result['url'])
|
| 73 |
+
processed_result['additional_content'] = additional_content[:5000] # Limit content length
|
| 74 |
+
|
| 75 |
+
processed_results.append(processed_result)
|
| 76 |
+
|
| 77 |
+
# Save processed results
|
| 78 |
+
output_file = PROCESSED_DIR / f"{category}_processed.json"
|
| 79 |
+
with open(output_file, 'w') as f:
|
| 80 |
+
json.dump(processed_results, f, indent=2)
|
| 81 |
+
|
| 82 |
+
# Also save as CSV for easy viewing
|
| 83 |
+
df = pd.DataFrame(processed_results)
|
| 84 |
+
df.to_csv(PROCESSED_DIR / f"{category}_processed.csv", index=False)
|
| 85 |
+
|
| 86 |
+
self.processed_data[category] = processed_results
|
| 87 |
+
return processed_results
|
| 88 |
+
|
| 89 |
+
def process_all_categories(self) -> Dict[str, List[Dict]]:
|
| 90 |
+
"""Process all categories"""
|
| 91 |
+
categories = [f.stem.replace('_results', '')
|
| 92 |
+
for f in RAW_DIR.glob('*_results.json')]
|
| 93 |
+
|
| 94 |
+
for category in categories:
|
| 95 |
+
logging.info(f"Processing category: {category}")
|
| 96 |
+
self.process_category(category)
|
| 97 |
+
|
| 98 |
+
# Save combined results
|
| 99 |
+
all_results = []
|
| 100 |
+
for category_results in self.processed_data.values():
|
| 101 |
+
all_results.extend(category_results)
|
| 102 |
+
|
| 103 |
+
combined_df = pd.DataFrame(all_results)
|
| 104 |
+
combined_df.to_csv(PROCESSED_DIR / "all_processed.csv", index=False)
|
| 105 |
+
|
| 106 |
+
# Generate and save statistics
|
| 107 |
+
stats = {
|
| 108 |
+
'total_results': len(all_results),
|
| 109 |
+
'results_per_category': {
|
| 110 |
+
category: len(results)
|
| 111 |
+
for category, results in self.processed_data.items()
|
| 112 |
+
},
|
| 113 |
+
'domains_distribution': combined_df['domain'].value_counts().to_dict(),
|
| 114 |
+
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
with open(PROCESSED_DIR / "processing_stats.json", 'w') as f:
|
| 118 |
+
json.dump(stats, f, indent=2)
|
| 119 |
+
|
| 120 |
+
return self.processed_data
|
requirements.txt
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# API Clients
|
| 2 |
+
google-generativeai==0.8.3
|
| 3 |
+
google-search-results==2.4.2
|
| 4 |
+
|
| 5 |
+
# Data Processing
|
| 6 |
+
pandas==2.2.3
|
| 7 |
+
numpy==2.2.0
|
| 8 |
+
|
| 9 |
+
# Web Scraping
|
| 10 |
+
beautifulsoup4==4.12.3
|
| 11 |
+
requests==2.32.3
|
| 12 |
+
|
| 13 |
+
# Progress Bars and Utils
|
| 14 |
+
tqdm==4.67.1
|
| 15 |
+
ratelimit==2.2.1
|
| 16 |
+
|
| 17 |
+
# Date and Time
|
| 18 |
+
python-dateutil==2.9.0
|
| 19 |
+
|
| 20 |
+
# Output Formatting
|
| 21 |
+
tabulate==0.9.0 # For nice DataFrame display
|
| 22 |
+
|
| 23 |
+
# Optional but recommended for better HTML parsing
|
| 24 |
+
lxml==5.3.0
|
scraper.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import time
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from typing import Dict, List
|
| 5 |
+
import logging
|
| 6 |
+
from serpapi import GoogleSearch
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from config import (
|
| 10 |
+
SERP_API_KEY, SERP_MONTHLY_LIMIT, SEARCH_QUERIES,
|
| 11 |
+
RAW_DIR, LOG_DIR
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
class BloomingtonScraper:
|
| 15 |
+
def __init__(self):
|
| 16 |
+
self.search_count = 0
|
| 17 |
+
self.results_by_category = {}
|
| 18 |
+
|
| 19 |
+
# Set up logging
|
| 20 |
+
log_file = LOG_DIR / f"scraper_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
|
| 21 |
+
logging.basicConfig(
|
| 22 |
+
level=logging.INFO,
|
| 23 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 24 |
+
filename=log_file
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def _make_serp_request(self, query: str, category: str) -> List[Dict]:
|
| 28 |
+
"""Make a single SERP API request"""
|
| 29 |
+
if self.search_count >= SERP_MONTHLY_LIMIT:
|
| 30 |
+
logging.warning("Monthly SERP API limit reached")
|
| 31 |
+
return []
|
| 32 |
+
|
| 33 |
+
params = {
|
| 34 |
+
"api_key": SERP_API_KEY,
|
| 35 |
+
"engine": "google",
|
| 36 |
+
"q": query,
|
| 37 |
+
"location": "Bloomington, Indiana, United States",
|
| 38 |
+
"google_domain": "google.com",
|
| 39 |
+
"num": 100, # Get maximum results per query
|
| 40 |
+
"start": 0
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
search = GoogleSearch(params)
|
| 45 |
+
results = search.get_dict()
|
| 46 |
+
self.search_count += 1
|
| 47 |
+
|
| 48 |
+
# Save raw results
|
| 49 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 50 |
+
raw_file = RAW_DIR / f"raw_results_{category}_{timestamp}.json"
|
| 51 |
+
with open(raw_file, 'w') as f:
|
| 52 |
+
json.dump(results, f, indent=2)
|
| 53 |
+
|
| 54 |
+
logging.info(f"SERP API calls used: {self.search_count}/{SERP_MONTHLY_LIMIT}")
|
| 55 |
+
return results.get('organic_results', [])
|
| 56 |
+
|
| 57 |
+
except Exception as e:
|
| 58 |
+
logging.error(f"SERP API error for query '{query}': {e}")
|
| 59 |
+
return []
|
| 60 |
+
|
| 61 |
+
def scrape_all_categories(self) -> Dict[str, List[Dict]]:
|
| 62 |
+
"""Scrape data for all categories"""
|
| 63 |
+
for category, queries in SEARCH_QUERIES.items():
|
| 64 |
+
logging.info(f"Starting scraping for category: {category}")
|
| 65 |
+
category_results = []
|
| 66 |
+
|
| 67 |
+
for query in queries:
|
| 68 |
+
if self.search_count >= SERP_MONTHLY_LIMIT:
|
| 69 |
+
logging.warning(f"Monthly limit reached during {category} scraping")
|
| 70 |
+
break
|
| 71 |
+
|
| 72 |
+
results = self._make_serp_request(query, category)
|
| 73 |
+
category_results.extend(results)
|
| 74 |
+
time.sleep(2) # Polite delay between requests
|
| 75 |
+
|
| 76 |
+
self.results_by_category[category] = category_results
|
| 77 |
+
|
| 78 |
+
# Save category results
|
| 79 |
+
category_file = RAW_DIR / f"{category}_results.json"
|
| 80 |
+
with open(category_file, 'w') as f:
|
| 81 |
+
json.dump(category_results, f, indent=2)
|
| 82 |
+
|
| 83 |
+
logging.info(f"Completed scraping for {category}: {len(category_results)} results")
|
| 84 |
+
|
| 85 |
+
return self.results_by_category
|
| 86 |
+
|
| 87 |
+
def get_search_stats(self) -> Dict:
|
| 88 |
+
"""Get statistics about the search results"""
|
| 89 |
+
stats = {
|
| 90 |
+
"total_searches": self.search_count,
|
| 91 |
+
"remaining_searches": SERP_MONTHLY_LIMIT - self.search_count,
|
| 92 |
+
"results_per_category": {
|
| 93 |
+
category: len(results)
|
| 94 |
+
for category, results in self.results_by_category.items()
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
# Save stats
|
| 99 |
+
stats_file = RAW_DIR / "search_stats.json"
|
| 100 |
+
with open(stats_file, 'w') as f:
|
| 101 |
+
json.dump(stats, f, indent=2)
|
| 102 |
+
|
| 103 |
+
return stats
|