Datasets:
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- .gitignore +9 -0
- LICENSE +202 -0
- README.md +167 -0
- construction/README.md +60 -0
- construction/annotate.py +533 -0
- construction/generate_terms.py +227 -0
- construction/intent_analysis.py +151 -0
- construction/pooling.py +153 -0
- construction/query_filter.py +563 -0
- construction/retrieve_candidates.py +101 -0
- construction/utils.py +347 -0
- data/README.md +25 -0
- data/baseline/qwen3_vl_embedding_8b_top50.json +0 -0
- data/baseline/qwen3_vl_reranker_8b_top50.json +0 -0
- data/images/product_images/000141ffc3d968e5.jpg +3 -0
- data/images/product_images/0006623597fe4213.jpg +3 -0
- data/images/product_images/000775e4cb9e5bee.jpg +3 -0
- data/images/product_images/00081bd03b1e69bc.jpg +3 -0
- data/images/product_images/00086a198e7e3720.jpg +3 -0
- data/images/product_images/0010f82ecfcecd62.jpg +3 -0
- data/images/product_images/00111db572ce2424.jpg +3 -0
- data/images/product_images/0011beb14ff9c526.jpg +3 -0
- data/images/product_images/00158ff2ea36023b.jpg +3 -0
- data/images/product_images/0017ed7e7c7bc2a3.jpg +3 -0
- data/images/product_images/0018037a3d23186d.jpg +3 -0
- data/images/product_images/001d2bccf8ac8ae1.jpg +3 -0
- data/images/product_images/00232ef0569c5e45.jpg +3 -0
- data/images/product_images/002acec3b6a8e31a.jpg +3 -0
- data/images/product_images/002e059a9eacc8d3.jpg +3 -0
- data/images/product_images/002e837a45283524.jpg +3 -0
- data/images/product_images/002ff89c71d2926d.jpg +3 -0
- data/images/product_images/00349e1c137b59a7.jpg +3 -0
- data/images/product_images/0035b57acec1f213.jpg +3 -0
- data/images/product_images/00366bfa06ee7744.jpg +3 -0
- data/images/product_images/003850fa8ca517d1.jpg +3 -0
- data/images/product_images/003dfb4e0c85d7e7.jpg +3 -0
- data/images/product_images/00409c85919a3b23.jpg +3 -0
- data/images/product_images/0042d6c8a8f54f8e.jpg +3 -0
- data/images/product_images/004367b9f70249fd.jpg +3 -0
- data/images/product_images/0045d2477c93508b.jpg +3 -0
- data/images/product_images/0046ff19c63a1516.jpg +3 -0
- data/images/product_images/0047608eca71adc7.jpg +3 -0
- data/images/product_images/004b916e301ba550.jpg +3 -0
- data/images/product_images/004cee587cb7e532.jpg +3 -0
- data/images/product_images/004fd209343d8145.jpg +3 -0
- data/images/product_images/004fea38f2d55e28.jpg +3 -0
- data/images/product_images/005310cc94a625ed.jpg +3 -0
- data/images/product_images/00534ab388a2fae5.jpg +3 -0
- data/images/product_images/00541941dd61a731.jpg +3 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
data/images/product_images/0197e751f99c867a.heic filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
data/images/product_images/02273861b0bbc94b.heic filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
.DS_Store
|
| 4 |
+
.env
|
| 5 |
+
.env.*
|
| 6 |
+
evaluation/outputs/
|
| 7 |
+
runs/
|
| 8 |
+
work/
|
| 9 |
+
models.json
|
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
README.md
CHANGED
|
@@ -1,3 +1,170 @@
|
|
| 1 |
---
|
|
|
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
pretty_name: MIPR
|
| 3 |
license: apache-2.0
|
| 4 |
+
language:
|
| 5 |
+
- zh
|
| 6 |
+
size_categories:
|
| 7 |
+
- 10K<n<100K
|
| 8 |
+
task_categories:
|
| 9 |
+
- text-retrieval
|
| 10 |
+
tags:
|
| 11 |
+
- image
|
| 12 |
+
- text
|
| 13 |
+
- multimodal-retrieval
|
| 14 |
+
- e-commerce
|
| 15 |
+
- intent-understanding
|
| 16 |
+
- multi-category
|
| 17 |
+
- benchmark
|
| 18 |
+
configs:
|
| 19 |
+
- config_name: queries
|
| 20 |
+
default: true
|
| 21 |
+
data_files:
|
| 22 |
+
- split: test
|
| 23 |
+
path: data/mipr_query.jsonl
|
| 24 |
+
- config_name: corpus
|
| 25 |
+
data_files:
|
| 26 |
+
- split: test
|
| 27 |
+
path: data/mipr_corpus.jsonl
|
| 28 |
+
- config_name: qrels
|
| 29 |
+
data_files:
|
| 30 |
+
- split: test
|
| 31 |
+
path: data/mipr_annotation.jsonl
|
| 32 |
---
|
| 33 |
+
|
| 34 |
+
# MIPR: A Benchmark for Reasoning-Intensive Multimodal Intent-to-Product Retrieval with Multi-Category Solutions
|
| 35 |
+
|
| 36 |
+
This repository contains the dataset, evaluation code and construction pipeline for **MIPR**, a benchmark for multimodal intent-to-product retrieval in Chinese e-commerce.
|
| 37 |
+
|
| 38 |
+
## Overview
|
| 39 |
+
|
| 40 |
+
Real-world shopping queries often describe a problem without naming the product that would solve it. MIPR pairs a situational image with a free-form question and asks models to retrieve products that satisfy the underlying need. The image need not show the desired product, and valid solutions can span multiple product categories.
|
| 41 |
+
|
| 42 |
+
Built from real Taobao search queries and product listings, MIPR evaluates intent reasoning, product relevance and coverage of different solution categories. Queries and products are in Chinese.
|
| 43 |
+
|
| 44 |
+
| Item | Count |
|
| 45 |
+
|---|---|
|
| 46 |
+
| Queries (image + question) | 3,522 |
|
| 47 |
+
| Unique query images | 3,013 |
|
| 48 |
+
| Products in the shared corpus | 30,731 |
|
| 49 |
+
| Query–product relevance judgments | 447,809 |
|
| 50 |
+
| Relevance levels | 5 |
|
| 51 |
+
|
| 52 |
+
MIPR is an evaluation benchmark with no predefined training split. The three Hugging Face configurations—`queries`, `corpus` and `qrels`—expose its component tables under the `test` split.
|
| 53 |
+
|
| 54 |
+
## Relevance Labels
|
| 55 |
+
|
| 56 |
+
| Label | Meaning |
|
| 57 |
+
|---|---|
|
| 58 |
+
| **L1** | Optimal solution: satisfies the underlying need and its key constraints |
|
| 59 |
+
| **L2** | Suboptimal solution: relevant but only partially satisfies the need |
|
| 60 |
+
| **N1** | Constraint-violating: appears applicable but violates a critical constraint |
|
| 61 |
+
| **N2** | Related non-solution: related by category or appearance but does not solve the need |
|
| 62 |
+
| **N3** | Irrelevant |
|
| 63 |
+
|
| 64 |
+
## Dataset Structure
|
| 65 |
+
|
| 66 |
+
```text
|
| 67 |
+
data/
|
| 68 |
+
├── mipr_query.jsonl
|
| 69 |
+
├── mipr_corpus.jsonl
|
| 70 |
+
├── mipr_annotation.jsonl
|
| 71 |
+
├── images/
|
| 72 |
+
│ ├── query_images/
|
| 73 |
+
│ └── product_images/
|
| 74 |
+
└── baseline/
|
| 75 |
+
├── qwen3_vl_embedding_8b_top50.json
|
| 76 |
+
└── qwen3_vl_reranker_8b_top50.json
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
All three data tables use JSON Lines. `idx` joins queries to qrels, and `item_id` joins qrels to the product corpus. Product IDs are hashed and query IDs are renumbered.
|
| 80 |
+
|
| 81 |
+
**Queries** (`queries`):
|
| 82 |
+
|
| 83 |
+
```json
|
| 84 |
+
{"idx": "1", "query": "表面的老垢用啥清洗剂除", "image_url": "1.jpg"}
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
**Products** (`corpus`):
|
| 88 |
+
|
| 89 |
+
```json
|
| 90 |
+
{"item_id": "4f0114c9a825e418", "title": "凯易牌除垢剂水垢清除剂制冰机专用KAY除垢剂商用去垢清洁剂", "pict_url": "4f0114c9a825e418.jpg", "treecate_full_path": "家清-环境清洁-清洁剂-除垢剂"}
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
**Relevance judgments** (`qrels`, shortened example):
|
| 94 |
+
|
| 95 |
+
```json
|
| 96 |
+
{"idx": "1", "items": [{"item_id": "4f0114c9a825e418", "final_grade": "L1"}]}
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
Each qrels row contains all judged products for one query; the 447,809 judgments are nested in 3,522 rows. `image_url` and `pict_url` are local filenames under `data/images/query_images/` and `data/images/product_images/`, respectively. They are not remote URLs. `treecate_full_path` provides the leaf category used for solution-category evaluation.
|
| 100 |
+
|
| 101 |
+
## Getting Started
|
| 102 |
+
|
| 103 |
+
Download the repository and run commands from its root. To load the tables locally with Hugging Face Datasets:
|
| 104 |
+
|
| 105 |
+
```bash
|
| 106 |
+
pip install datasets
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
```python
|
| 110 |
+
from datasets import load_dataset
|
| 111 |
+
|
| 112 |
+
queries = load_dataset("json", data_files={"test": "data/mipr_query.jsonl"}, split="test")
|
| 113 |
+
corpus = load_dataset("json", data_files={"test": "data/mipr_corpus.jsonl"}, split="test")
|
| 114 |
+
qrels = load_dataset("json", data_files={"test": "data/mipr_annotation.jsonl"}, split="test")
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
### Evaluate the bundled rankings
|
| 118 |
+
|
| 119 |
+
The saved rankings allow evaluation without model inference or extra dependencies:
|
| 120 |
+
|
| 121 |
+
```bash
|
| 122 |
+
python evaluation/evaluate.py data/baseline/qwen3_vl_embedding_8b_top50.json
|
| 123 |
+
python evaluation/evaluate.py data/baseline/qwen3_vl_reranker_8b_top50.json --rerank
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
| System | nDCG@10 | R-L1@10 | Hit-L1@1 | Hit-L1@10 | SC-R-L1@10 | SC-R-L1@10* |
|
| 127 |
+
|---|---|---|---|---|---|---|
|
| 128 |
+
| Qwen3-VL-Embedding-8B | 49.23 | 53.98 | 47.02 | 85.63 | 61.33 | 55.86 |
|
| 129 |
+
| Qwen3-VL-Reranker-8B | 60.11 | 66.00 | 59.26 | 91.25 | 71.52 | 67.00 |
|
| 130 |
+
| Candidate-pool Oracle | 86.04 | 78.95 | 94.97 | 94.97 | 82.80 | 80.22 |
|
| 131 |
+
|
| 132 |
+
Scores are multiplied by 100. nDCG uses gains L1=2 and L2=1; R-L1 measures recall of judged L1 products; Hit-L1 measures whether an L1 product is retrieved; SC-R-L1 measures coverage of judged L1 leaf categories. The starred metric uses the 2,664 queries with at least two L1 categories. Reranking and the Oracle operate on the embedding model's top-50 candidates.
|
| 133 |
+
|
| 134 |
+
### Evaluate your own model
|
| 135 |
+
|
| 136 |
+
```bash
|
| 137 |
+
pip install -r requirements.txt
|
| 138 |
+
python evaluation/embedding.py --model Qwen/Qwen3-VL-Embedding-8B --out runs/embedding
|
| 139 |
+
python evaluation/retrieval.py --embed-dir runs/embedding --output runs/retrieval.json
|
| 140 |
+
python evaluation/evaluate.py runs/retrieval.json
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Custom runs are JSON arrays with one entry per query:
|
| 144 |
+
|
| 145 |
+
```json
|
| 146 |
+
[{"qid": "1", "ranked": [{"did": "4f0114c9a825e418", "score": 0.87}]}]
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
All queries must appear exactly once, ranked product IDs must belong to the shared corpus, and scores are optional. For reranking, preserve the baseline candidate pool. See the [evaluation guide](evaluation/README.md) for reranker commands, supported models and analysis metrics.
|
| 150 |
+
|
| 151 |
+
## Construction and Scope
|
| 152 |
+
|
| 153 |
+
Construction combines query filtering and intent analysis, two-round product-term generation, multi-route retrieval, deduplication, three-model relevance labeling with Sonnet adjudication, and retrieval-based pooling. The [construction code](construction/README.md) includes the prompts and stage commands; source data, model services and the retrieval backend must be supplied separately.
|
| 154 |
+
|
| 155 |
+
Relevance judgments cover the discovered and pooled candidates rather than every possible query–product pair. Unjudged pairs receive zero gain during evaluation. The benchmark reflects Chinese e-commerce queries and the supplied product corpus; its solution categories are the annotated categories, not an exhaustive list of all possible solutions.
|
| 156 |
+
|
| 157 |
+
## Citation
|
| 158 |
+
|
| 159 |
+
If you use MIPR, please cite:
|
| 160 |
+
|
| 161 |
+
```bibtex
|
| 162 |
+
@misc{li_mipr,
|
| 163 |
+
title = {MIPR: A Benchmark for Reasoning-Intensive Multimodal Intent-to-Product Retrieval with Multi-Category Solutions},
|
| 164 |
+
author = {Qiang Li and Xuan Lu and Jian Ruan and Manxi Lin and Jiacheng Chen and Wen Shen and Zhihua Wei and Xiaoyu Shen and Dan Ou and Xiangheng Kong and Junjun Zheng}
|
| 165 |
+
}
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
## License
|
| 169 |
+
|
| 170 |
+
The dataset and code are released under the [Apache License 2.0](LICENSE).
|
construction/README.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIPR construction
|
| 2 |
+
|
| 3 |
+
Scripts and prompts for constructing MIPR from multimodal queries and a product catalog.
|
| 4 |
+
|
| 5 |
+
| File | Function |
|
| 6 |
+
|---|---|
|
| 7 |
+
| `query_filter.py` | Rules → coarse filtering → dual-model fine filtering → query deduplication |
|
| 8 |
+
| `intent_analysis.py` | Image-grounded intent analysis through `claude -p` |
|
| 9 |
+
| `generate_terms.py` | Two-round product-term generation with Qwen3.6-27B / vLLM |
|
| 10 |
+
| `retrieve_candidates.py` | Multi-route retrieval → within-leaf product deduplication → candidate redirection |
|
| 11 |
+
| `annotate.py` | Coarse screening → three-model fine annotation → voting and Sonnet adjudication |
|
| 12 |
+
| `pooling.py` | Candidate pooling, unseen-pair preparation, result merging and final qrels |
|
| 13 |
+
| `utils.py` | Shared I/O, parsing, local-model and clustering helpers |
|
| 14 |
+
|
| 15 |
+
Query stages use JSONL with `idx`, `query`, `image_url` (local filename), and `scene: {content, intent, note}`; term generation adds `product_keywords`.
|
| 16 |
+
|
| 17 |
+
Deduplication uses Qwen3-Embedding-8B intent vectors for queries (threshold 0.70) and Qwen3-VL-Embedding-8B image/title vectors for products (within-leaf threshold 0.60). Cached vectors use NPZ fields `emb` and `ids`, in input order.
|
| 18 |
+
|
| 19 |
+
Supply source data, model weights and a retrieval backend implementing `search(mode, queries, top_k)`. Term generation uses `vllm`; query encoding uses `sentence-transformers`. Configure `claude -p` for the model names used by the scripts.
|
| 20 |
+
|
| 21 |
+
## Usage
|
| 22 |
+
|
| 23 |
+
Run commands from `construction/`; paths below are illustrative inputs/outputs.
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
python query_filter.py rules --input raw_queries.jsonl --output ruled.jsonl
|
| 27 |
+
python intent_analysis.py --input ruled.jsonl --image-dir query_images --output scenes.jsonl
|
| 28 |
+
python query_filter.py coarse --input scenes.jsonl --model-path /path/to/Qwen3.6-27B --output screened.jsonl
|
| 29 |
+
python query_filter.py fine --input screened.jsonl --model GLM-5.2 --output glm_queries.jsonl
|
| 30 |
+
python query_filter.py fine --input screened.jsonl --model deepseek-v4-pro --output ds_queries.jsonl
|
| 31 |
+
python query_filter.py merge --glm glm_queries.jsonl --ds ds_queries.jsonl --output eligible.jsonl
|
| 32 |
+
python query_filter.py dedup --input eligible.jsonl --output-dir query_dedup
|
| 33 |
+
python generate_terms.py --input query_dedup/deduplicated.jsonl --out-dir terms
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
Call `retrieve_candidates(input_path, output_path, search)` with `terms/terms_r2.jsonl` and your retrieval backend, saving the result as `sources.jsonl`. Encode the union of retrieved products, then deduplicate:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
python retrieve_candidates.py --input products.jsonl --emb-path products.npz --sources sources.jsonl --output-dir product_dedup
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
The resulting `pairs.jsonl` contains flat pairs: `{"idx": "1", "item_id": "p1", "retrieved_by": ["source"]}`. Use these pairs for annotation and pooling:
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
python annotate.py coarse --input product_dedup/pairs.jsonl --queries query_dedup/deduplicated.jsonl --corpus product_dedup/deduplicated.jsonl --output coarse.jsonl --model-path /path/to/Qwen3.6-27B
|
| 46 |
+
python annotate.py fine --input coarse.jsonl --queries query_dedup/deduplicated.jsonl --corpus product_dedup/deduplicated.jsonl --captions captions.jsonl --model deepseek-v4-pro --output ds.jsonl
|
| 47 |
+
# Repeat fine annotation for qwen3.7-max and GLM-5.2, producing qw.jsonl and glm.jsonl.
|
| 48 |
+
python annotate.py adjudicate --ds ds.jsonl --qw qw.jsonl --glm glm.jsonl --output-dir initial_labels
|
| 49 |
+
python pooling.py build --recall product_dedup/pairs.jsonl --runs runs/*/retrieval_top50.json --output pool.jsonl
|
| 50 |
+
python pooling.py prepare --pool pool.jsonl --coarse coarse.jsonl --done coarse_done.jsonl --todo unseen.jsonl
|
| 51 |
+
# Annotate unseen.jsonl as above, producing coarse_new.jsonl and new_labels/final.jsonl.
|
| 52 |
+
python pooling.py merge --pool pool.jsonl --results coarse_done.jsonl coarse_new.jsonl --output coarse_all.jsonl
|
| 53 |
+
python pooling.py finalize --pool pool.jsonl --coarse coarse_all.jsonl --fine initial_labels/final.jsonl new_labels/final.jsonl --queries query_dedup/deduplicated.jsonl --output-dir constructed
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
Fine annotation processes only coarse-kept pairs. Finalization assigns N3 to coarse rejects, normalizes the five labels and retains queries with 1–20 L1 products after pooling. Outputs are `mipr_query.jsonl`, `mipr_annotation.jsonl` and `pool_membership.jsonl`.
|
| 57 |
+
|
| 58 |
+
For the paper's pooling setup, supply all ten model runs at top-20, using the same query and product IDs as the construction inputs. The bundled evaluation rankings alone are insufficient to build this pool.
|
| 59 |
+
|
| 60 |
+
Query filtering consumes the original question and structured image/intent descriptions. Product-term generation uses two rounds with a maximum of seven terms. Fine annotation uses three models; polarity conflicts and three distinct labels are adjudicated by Sonnet.
|
construction/annotate.py
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""商品标注:粗筛 → 三模型精标 → 多数投票与 Sonnet 仲裁。"""
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import subprocess
|
| 7 |
+
import threading
|
| 8 |
+
import time
|
| 9 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from utils import parse_grade as parse_result
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
SYSTEM_PROMPT = "你是一个商品相关性精评助手。只输出 JSON 对象,不要输出任何解释或其他内容。"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
VALID_GRADES = {"L1", "L2", "hard_neg_lookalike", "hard_neg_constraint", "irrelevant"}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
_write_lock = threading.Lock()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def log(msg):
|
| 25 |
+
print(msg, flush=True)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load_jsonl(path):
|
| 29 |
+
rows = []
|
| 30 |
+
with open(path, encoding="utf-8") as f:
|
| 31 |
+
for line in f:
|
| 32 |
+
line = line.strip()
|
| 33 |
+
if line:
|
| 34 |
+
rows.append(json.loads(line))
|
| 35 |
+
return rows
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def cand_key(rec):
|
| 39 |
+
return f'{rec["idx"]}|{rec["item_id"]}'
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def load_done(path):
|
| 43 |
+
done = set()
|
| 44 |
+
if not path.exists():
|
| 45 |
+
return done
|
| 46 |
+
with open(path, encoding="utf-8") as f:
|
| 47 |
+
for line in f:
|
| 48 |
+
line = line.strip()
|
| 49 |
+
if not line:
|
| 50 |
+
continue
|
| 51 |
+
try:
|
| 52 |
+
r = json.loads(line)
|
| 53 |
+
done.add(cand_key(r))
|
| 54 |
+
except (json.JSONDecodeError, KeyError):
|
| 55 |
+
continue
|
| 56 |
+
return done
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def append_jsonl(path, obj):
|
| 60 |
+
with _write_lock:
|
| 61 |
+
with open(path, "a", encoding="utf-8") as f:
|
| 62 |
+
f.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
| 63 |
+
f.flush()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def load_scenes(path):
|
| 67 |
+
return {str(row["idx"]): {"question": row["query"], **row["scene"]}
|
| 68 |
+
for row in load_jsonl(path)}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def load_corpus(path):
|
| 72 |
+
return {str(row["item_id"]): row for row in load_jsonl(path)}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load_captions(path):
|
| 76 |
+
return {str(row["item_id"]): row["caption"] for row in load_jsonl(path)}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# 1. 粗筛。
|
| 80 |
+
COARSE_FILTER_PROMPT = """用户拍了一张图并提出需求,想买商品来解决。给你一个候选商品,只做宽松粗筛,区分“完全不沾边”和“沾边或可能有用”。
|
| 81 |
+
|
| 82 |
+
# 判断标准
|
| 83 |
+
- keep:商品与需求涉及的对象、用途或场景有联系,或可能有用。
|
| 84 |
+
- discard:商品与需求完全不沾边,明显没有关联(如:要保养玉石 → 却是厨房模具)。
|
| 85 |
+
|
| 86 |
+
# 注意
|
| 87 |
+
- 只排除完全无关的商品。商品可能有用、或你无法确定是否有关联时,一律 keep。
|
| 88 |
+
- 综合参考商品标题和类目;不要仅因类目不同就 discard,不同类目的商品也可能与需求有关联。
|
| 89 |
+
|
| 90 |
+
# 示例1
|
| 91 |
+
【用户】
|
| 92 |
+
图像内容:翡翠(或玉石)圆形平安扣吊坠,颜色为淡绿色,成色较浅,配有18K金扣头,整体品相较新
|
| 93 |
+
用户意图:寻找适合保养玉石/翡翠吊坠的养护用品
|
| 94 |
+
【商品】
|
| 95 |
+
标题:家用烘焙硅胶蛋糕模具 六连马芬杯
|
| 96 |
+
商品类目:厨房用品-烘焙用具-蛋糕模具
|
| 97 |
+
【输出】
|
| 98 |
+
{{"decision": "discard", "reason": "商品为烘焙蛋糕模具,与玉石保养完全无关"}}
|
| 99 |
+
|
| 100 |
+
# 示例2
|
| 101 |
+
【用户】
|
| 102 |
+
图像内容:翡翠(或玉石)圆形平安扣吊坠,颜色为淡绿色,成色较浅,配有18K金扣头,整体品相较新
|
| 103 |
+
用户意图:寻找适合保养玉石/翡翠吊坠的养护用品
|
| 104 |
+
【商品】
|
| 105 |
+
标题:铸固黄白抛光布轮首饰珠宝抛光布轮金属打磨不锈钢镜面抛光白色布
|
| 106 |
+
商品类目:五金-磨具-抛光轮
|
| 107 |
+
【输出】
|
| 108 |
+
{{"decision": "keep", "reason": "与珠宝养护沾边,是否适用玉石无法确定,保留"}}
|
| 109 |
+
|
| 110 |
+
# 本次输入
|
| 111 |
+
【用户】
|
| 112 |
+
图像内容:{content}
|
| 113 |
+
用户意图:{intent}
|
| 114 |
+
【商品】
|
| 115 |
+
标题:{title}
|
| 116 |
+
商品类目:{category}
|
| 117 |
+
【输出】
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def parse_decision(raw):
|
| 122 |
+
match = re.search(r"\{.*?\}", raw, re.DOTALL)
|
| 123 |
+
if match:
|
| 124 |
+
try:
|
| 125 |
+
obj = json.loads(match.group())
|
| 126 |
+
decision = obj.get("decision", "").lower()
|
| 127 |
+
if decision in ("keep", "discard"):
|
| 128 |
+
return decision, obj.get("reason", "")
|
| 129 |
+
except json.JSONDecodeError:
|
| 130 |
+
pass
|
| 131 |
+
raw_lower = raw.lower()
|
| 132 |
+
if "discard" in raw_lower:
|
| 133 |
+
return "discard", raw[:100]
|
| 134 |
+
return "keep", raw[:100]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def run_coarse(args):
|
| 138 |
+
from utils import load_model_and_processor, run_text_only_batch
|
| 139 |
+
pairs = load_jsonl(args.input)
|
| 140 |
+
scenes, corpus = load_scenes(args.queries), load_corpus(args.corpus)
|
| 141 |
+
out = Path(args.output)
|
| 142 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 143 |
+
done = load_done(out)
|
| 144 |
+
out.touch(exist_ok=True)
|
| 145 |
+
pairs = [pair for pair in pairs if cand_key(pair) not in done]
|
| 146 |
+
if not pairs:
|
| 147 |
+
return
|
| 148 |
+
model, processor = load_model_and_processor(args.model_path)
|
| 149 |
+
for start in range(0, len(pairs), 32):
|
| 150 |
+
chunk = pairs[start:start + 32]
|
| 151 |
+
prompts = []
|
| 152 |
+
for pair in chunk:
|
| 153 |
+
sc, product = scenes[str(pair["idx"])], corpus[str(pair["item_id"])]
|
| 154 |
+
prompts.append(COARSE_FILTER_PROMPT.format(
|
| 155 |
+
content=sc["content"], intent=sc["intent"],
|
| 156 |
+
title=product["title"], category=product["treecate_full_path"]))
|
| 157 |
+
responses = run_text_only_batch(model, processor, prompts, batch_size=32,
|
| 158 |
+
max_new_tokens=256, do_sample=False, show_progress=False)
|
| 159 |
+
for pair, response in zip(chunk, responses):
|
| 160 |
+
decision, reason = parse_decision(response)
|
| 161 |
+
append_jsonl(out, {**pair, "decision": decision, "reason": reason})
|
| 162 |
+
log(f"粗筛完成:{out}")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# 2. 五级精标。
|
| 166 |
+
FINE_FILTER_PROMPT_WITH_IMG = """用户拍了一张图并提出需求,想买商品来解决。给你一个候选商品,请对它做细致的相关性分级。
|
| 167 |
+
|
| 168 |
+
# 背景信息
|
| 169 |
+
- 图像内容:用户所拍图片的文字描述(即用户手上待解决问题的物品或场景)。
|
| 170 |
+
- 用户意图:用户真正想解决的问题。
|
| 171 |
+
- 商品标题 / 商品图描述 / 商品类目:候选商品的三项信息,含义见下方"信息使用原则"。
|
| 172 |
+
|
| 173 |
+
# 信息使用原则
|
| 174 |
+
- 商品标题:主要依据。商家会写明核心品名与主打场景,用它判断"这个商品是什么、干什么用的"。
|
| 175 |
+
- 商品图描述:商品实拍图的文字描述,反映商品的真实形态/外观(是膏状、喷雾、刷子还是别的)。用它佐证和补充标题——尤其当标题含糊或夸大时,以图描述看清商品实际是什么。若标题措辞夸张(如"神器""万能"),而图描述显示其真实形态与所需品类不符,应以图描述反映的实际商品为准。
|
| 176 |
+
- 商品类目:平台对商品的结构化归类,反映商品的品类归属,是重要的佐证依据。当标题堆砌关键词、图描述较泛时,类目能帮助锁定商品到底属于哪一类。注意类目有时会挂错或挂粗,因此当类目与标题、图描述明显矛盾时,以标题和图描述反映的实际商品为准。
|
| 177 |
+
- 三者相互印证,综合判断"商品实际是什么、能不能解决用户痛点":多数情况下三者一致;若不一致,优先信任标题与图描述共同反映的实际商品,类目作为品类归属的参考。
|
| 178 |
+
|
| 179 |
+
# 分级标准(按顺序判断,命中即停)
|
| 180 |
+
|
| 181 |
+
## 第一步:这个商品能不能解决用户的核心需求?
|
| 182 |
+
关键问自己:"用户拿到这个商品,能不能解决他最想解决的那个痛点?"
|
| 183 |
+
结合标题、图描述与类目,读懂商品整体是干什么用的、能不能解决用户真正的痛点,而不是看到标题里有个和需求相同的词就算能解决。
|
| 184 |
+
- 完全无关,和需求扯不上关系、毫无关联 → **irrelevant**
|
| 185 |
+
(例:要清洗鞋面,商品是"冰箱除味盒"——和洗鞋毫无关系)
|
| 186 |
+
- 解决不了核心需求:商品和需求沾边(同领域或名称相似、看着像能解决),但商品的实际用途干的不是解决用户痛点这件事 → **hard_neg_lookalike**
|
| 187 |
+
(例:要清洗鞋面,商品是"鞋撑/鞋盒"——它的用途是定型/收纳,不是清洗,解决不了洗鞋这个痛点)
|
| 188 |
+
- 能解决核心需求 → 进入第二步
|
| 189 |
+
|
| 190 |
+
## 第二步:能解决,但用了会不会损坏物品 / 造成伤害?
|
| 191 |
+
请结合用户图像中物品的材质/属性,凭常识判断:这个商品用于本需求,会不会损坏用户的物品、或造成安全/健康伤害?
|
| 192 |
+
- 商品能解决需求,但用于本需求会造成损坏或伤害 → **hard_neg_constraint**
|
| 193 |
+
(例:清洗深蓝色网面鞋,商品是"强漂白洗鞋剂"——能洗鞋(能解决),但会导致深色鞋面褪色,造成损坏)
|
| 194 |
+
- 不会造成损坏或伤害 → 进入第三步
|
| 195 |
+
|
| 196 |
+
## 第三步:专门对口(L1) 还是 通用凑合(L2)?
|
| 197 |
+
- 专门为这类需求设计、或标题主打了本需求场景的对口商品 → **L1**
|
| 198 |
+
(例:清洗网面鞋,商品是"运动鞋网面专用清洁剂")
|
| 199 |
+
- 通用商品能解决、但不够对口(不专用,但能用、无损坏)→ **L2**
|
| 200 |
+
(例:清洗网面鞋,商品是"洗衣香皂"——能洗、不含漂白无损坏风险,但非鞋面专用、不够对口)
|
| 201 |
+
|
| 202 |
+
# 判断原则(重要)
|
| 203 |
+
- 一切以【用户核心需求能否被解决】为准:完全不沾边→irrelevant;沾边但解决不了核心痛点→hard_neg_lookalike;能解决但会损坏/伤害→hard_neg_constraint;能解决且无损坏→正例(L1/L2)。
|
| 204 |
+
- 区分 irrelevant 与 lookalike:完全不沾边、和需求毫无关联的商品判 irrelevant(如洗鞋需求下的"冰箱除味盒");只有当商品和需求同领域/名称相似、看着像能解决但实际用途不对时,才判 hard_neg_lookalike(如洗鞋需求下的"鞋撑")。二者区别在于"沾不沾边"。
|
| 205 |
+
- 读懂商品整体是做什么的,抓住核心痛点:综合标题、图描述与类目理解商品的实际用途,看它到底能不能解决用户真正要解决的问题。例如需求是"清洗鞋面"、标题是"擦鞋神器"但图描述显示是"一把软毛刷子"、类目为"鞋刷",则实际是鞋刷、并非清洗剂,应判 hard_neg_lookalike。
|
| 206 |
+
- 损坏/伤害的判断要基于确实存在的风险,不要过度联想:普通商品用于常规用途一般不构成损坏(如用普通胶水补掉钻,只是不够牢固→仍属能解决,判L2),只有确实会毁坏物品或危害安全健康时才判 hard_neg_constraint。
|
| 207 |
+
|
| 208 |
+
# 以下示例均基于同一个需求:清洗网面运动鞋
|
| 209 |
+
|
| 210 |
+
【共同输入】
|
| 211 |
+
图像内容:一双斯凯奇运动休闲鞋,鞋面为深蓝色网布/飞织材质,白色厚底
|
| 212 |
+
用户意图:寻找清洗运动鞋网面(飞织/网布鞋面)的清洗剂
|
| 213 |
+
|
| 214 |
+
# 示例1(L1:专门对口)
|
| 215 |
+
【商品】
|
| 216 |
+
标题:多用去污膏去除顽固污渍网面鞋家用去污多功能清洁膏擦鞋神器
|
| 217 |
+
图描述:一盒白色膏状清洁产品,配有海绵,包装标注"网面鞋去污"
|
| 218 |
+
类目:家清-环境清洁-清洁剂-多用途清洁剂
|
| 219 |
+
【输出】
|
| 220 |
+
{{"grade": "L1", "reason": "标题、图描述、类目三者一致——是膏状去污清洁品、能清洗鞋面顽固污渍解决核心需求,标题主打'网面鞋去污'、图描述确认为清洁膏、类目为清洁剂,锚定洗鞋场景,专门对口"}}
|
| 221 |
+
|
| 222 |
+
# 示例2(L2:通用凑合)
|
| 223 |
+
【商品】
|
| 224 |
+
标题:千里臣洗衣液温和不伤手婴幼儿新生儿童宝宝母婴专用洗衣液
|
| 225 |
+
图描述:一瓶蓝色包装的洗衣液,瓶身标注"婴幼儿专用"
|
| 226 |
+
类目:家清-衣物洗护-洗衣液-普通洗衣液
|
| 227 |
+
【输出】
|
| 228 |
+
{{"grade": "L2", "reason": "标题、图描述、类目均指向婴幼儿洗衣液,能清洗织物污渍、可用于清洗网布鞋面、解决核心需求,温和不含漂白无损坏风险,但是无场景锚定的通用洗涤品、非鞋面专用,不够对口"}}
|
| 229 |
+
|
| 230 |
+
# 示例3(hard_neg_constraint:能解决但会损坏)
|
| 231 |
+
【商品】
|
| 232 |
+
标题:立白漂白水600g
|
| 233 |
+
图描述:一瓶白色漂白水,瓶身标注"漂白"字样
|
| 234 |
+
类目:家清-衣物洗护-漂白剂
|
| 235 |
+
【输出】
|
| 236 |
+
{{"grade": "hard_neg_constraint", "reason": "标题、图描述、类目一致确认为漂白水,能清洗鞋面污渍(能解决核心需求),但用户鞋面为深蓝色、漂白会导致褪色,用于本需求会损坏鞋子,属会造成损坏的红线"}}
|
| 237 |
+
|
| 238 |
+
# 示例4(hard_neg_lookalike:解决不了核心需求)
|
| 239 |
+
【商品】
|
| 240 |
+
标题:家用鞋子除臭喷雾剂银离子清新剂学生宿舍去异味持久清香防臭杀菌
|
| 241 |
+
图描述:一瓶喷雾式除味剂,标注"鞋类除臭、持久清香"
|
| 242 |
+
类目:家清-衣物洗护-鞋袜除臭剂
|
| 243 |
+
【输出】
|
| 244 |
+
{{"grade": "hard_neg_lookalike", "reason": "标题、图描述、类目均显示是鞋类除臭剂,虽同为鞋类护理、词面都含'鞋',但实际用途是去除鞋内异味,用户核心需求是清洗鞋面污渍,除臭剂解决不了'洗干净'这个痛点,无法解决需求"}}
|
| 245 |
+
|
| 246 |
+
# 示例5(hard_neg_lookalike:标题夸大,图描述与类目揭示实为工具)
|
| 247 |
+
【商品】
|
| 248 |
+
标题:擦鞋神器网面鞋清洁去污一擦即净家用清洁好帮手
|
| 249 |
+
图描述:一把带手柄的软毛刷子
|
| 250 |
+
类目:日用百货-刷子-鞋刷
|
| 251 |
+
【输出】
|
| 252 |
+
{{"grade": "hard_neg_lookalike", "reason": "标题措辞夸张称'擦鞋神器/清洁去污'、看似清洁剂,但图描述显示实为一把软毛刷子、类目也归为'鞋刷',可判定实际是鞋刷工具而非清洗剂;用户核心需求是找清洗剂,鞋刷不属于该品类,解决不了需求"}}
|
| 253 |
+
|
| 254 |
+
# 示例6(irrelevant:完全无关)
|
| 255 |
+
【商品】
|
| 256 |
+
标题:冰箱除味盒活性炭去异味保鲜盒厨房家用除味剂
|
| 257 |
+
图描述:一个白色塑料盒,内含活性炭,用于冰箱内除味
|
| 258 |
+
类目:家清-空气清新-除味剂
|
| 259 |
+
【输出】
|
| 260 |
+
{{"grade": "irrelevant", "reason": "标题、图描述、类目均指向冰箱除味盒,用于冰箱内除味保鲜,和清洗鞋面这个需求毫无关联、完全不沾边,判 irrelevant"}}
|
| 261 |
+
|
| 262 |
+
# 本次输入
|
| 263 |
+
【用户】
|
| 264 |
+
图像内容:{content}
|
| 265 |
+
原始问题:{question}
|
| 266 |
+
用户意图:{intent}
|
| 267 |
+
【商品】
|
| 268 |
+
标题:{title}
|
| 269 |
+
图描述:{product_caption}
|
| 270 |
+
类目:{category}
|
| 271 |
+
【输出】
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
MODEL_NAMES = {
|
| 276 |
+
"ds": "deepseek-v4-pro",
|
| 277 |
+
"qw": "qwen3.7-max",
|
| 278 |
+
"glm": "GLM-5.2",
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def call_claude(prompt, model, timeout_seconds):
|
| 283 |
+
result = subprocess.run(
|
| 284 |
+
[
|
| 285 |
+
"claude", "-p", prompt,
|
| 286 |
+
"--system-prompt", SYSTEM_PROMPT,
|
| 287 |
+
"--model", model,
|
| 288 |
+
"--output-format", "text",
|
| 289 |
+
"--no-session-persistence",
|
| 290 |
+
"--bare",
|
| 291 |
+
],
|
| 292 |
+
stdin=subprocess.DEVNULL,
|
| 293 |
+
capture_output=True,
|
| 294 |
+
text=True,
|
| 295 |
+
timeout=timeout_seconds,
|
| 296 |
+
)
|
| 297 |
+
if result.returncode != 0:
|
| 298 |
+
stderr = (result.stderr or "").strip()
|
| 299 |
+
raise RuntimeError(f"claude -p exit {result.returncode}: {stderr}")
|
| 300 |
+
return result.stdout.strip()
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def call_claude_with_retry(prompt, model, max_retries, timeout_seconds):
|
| 304 |
+
for attempt in range(1, max_retries + 1):
|
| 305 |
+
try:
|
| 306 |
+
raw = call_claude(prompt, model, timeout_seconds)
|
| 307 |
+
parse_result(raw) # Invalid responses are retried, never converted to L2.
|
| 308 |
+
return raw, None
|
| 309 |
+
except Exception as exc:
|
| 310 |
+
if attempt == max_retries:
|
| 311 |
+
return None, str(exc)
|
| 312 |
+
time.sleep(min(2 ** attempt, 10))
|
| 313 |
+
return None, "max retries exceeded"
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def build_prompt(pair, scenes, corpus, captions):
|
| 317 |
+
idx = str(pair["idx"])
|
| 318 |
+
item_id = str(pair["item_id"])
|
| 319 |
+
sc = scenes.get(idx, {})
|
| 320 |
+
corp = corpus.get(item_id, {})
|
| 321 |
+
cap = captions.get(item_id, "")
|
| 322 |
+
return FINE_FILTER_PROMPT_WITH_IMG.format(
|
| 323 |
+
question=sc["question"],
|
| 324 |
+
content=sc.get("content", ""),
|
| 325 |
+
intent=sc.get("intent", ""),
|
| 326 |
+
title=corp.get("title", ""),
|
| 327 |
+
product_caption=cap,
|
| 328 |
+
category=corp.get("treecate_full_path", ""),
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def run_fine(args):
|
| 333 |
+
pairs = load_jsonl(args.input)
|
| 334 |
+
if any("decision" in pair and pair["decision"] not in {"keep", "discard"} for pair in pairs):
|
| 335 |
+
raise ValueError("Invalid coarse decision")
|
| 336 |
+
pairs = [pair for pair in pairs if pair.get("decision", "keep") == "keep"]
|
| 337 |
+
scenes, corpus = load_scenes(args.queries), load_corpus(args.corpus)
|
| 338 |
+
captions = load_captions(args.captions)
|
| 339 |
+
output_path = Path(args.output)
|
| 340 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 341 |
+
done = load_done(output_path)
|
| 342 |
+
output_path.touch(exist_ok=True)
|
| 343 |
+
|
| 344 |
+
def process_one(pair):
|
| 345 |
+
idx, item_id = str(pair["idx"]), str(pair["item_id"])
|
| 346 |
+
sc, product = scenes[idx], corpus[item_id]
|
| 347 |
+
prompt = build_prompt(pair, scenes, corpus, captions)
|
| 348 |
+
raw, error = call_claude_with_retry(prompt, args.model, args.max_retries, args.timeout)
|
| 349 |
+
if error:
|
| 350 |
+
raise RuntimeError(f"{cand_key(pair)}: {error}")
|
| 351 |
+
append_jsonl(output_path, {
|
| 352 |
+
"idx": idx, "item_id": item_id, "retrieved_by": pair.get("retrieved_by", []),
|
| 353 |
+
"question": sc["question"], "content": sc["content"], "intent": sc["intent"],
|
| 354 |
+
"title": product["title"], "treecate_full_path": product["treecate_full_path"],
|
| 355 |
+
"product_caption": captions[item_id], **parse_result(raw), "raw_response": raw,
|
| 356 |
+
})
|
| 357 |
+
|
| 358 |
+
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
| 359 |
+
futures = [pool.submit(process_one, pair) for pair in pairs if cand_key(pair) not in done]
|
| 360 |
+
for future in as_completed(futures):
|
| 361 |
+
future.result()
|
| 362 |
+
log(f"精标完成:{output_path}")
|
| 363 |
+
return output_path
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
# 3. 投票与分歧仲裁:共用精标标准及示例。
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
SONNET_JUDGE_PROMPT = FINE_FILTER_PROMPT_WITH_IMG.rsplit("【输出】", 1)[0] + """
|
| 370 |
+
# 三个模型的评估结果(仅供参考)
|
| 371 |
+
|
| 372 |
+
以下是三个模型对本商品的独立评估结果。它们产生了分歧,请参考它们的判断和理由,独立思考后给出你的最终判断。
|
| 373 |
+
|
| 374 |
+
模型A ({name_a}):
|
| 375 |
+
- 评级:{grade_a}
|
| 376 |
+
- 理由:{reason_a}
|
| 377 |
+
|
| 378 |
+
模型B ({name_b}):
|
| 379 |
+
- 评级:{grade_b}
|
| 380 |
+
- 理由:{reason_b}
|
| 381 |
+
|
| 382 |
+
模型C ({name_c}):
|
| 383 |
+
- 评级:{grade_c}
|
| 384 |
+
- 理由:{reason_c}
|
| 385 |
+
|
| 386 |
+
请综合以上信息,给出你的最终评级和理由。
|
| 387 |
+
【输出】
|
| 388 |
+
"""
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def merge_votes(votes):
|
| 392 |
+
grades = list(votes.values())
|
| 393 |
+
if len(grades) != 3 or any(grade not in VALID_GRADES for grade in grades):
|
| 394 |
+
raise ValueError("需要三个有效的五级标签")
|
| 395 |
+
positive = {grade in {"L1", "L2"} for grade in grades}
|
| 396 |
+
if len(positive) > 1 or len(set(grades)) == 3:
|
| 397 |
+
return "disagree", None
|
| 398 |
+
return "agree", max(grades, key=grades.count)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def do_merge(model_paths, merged_path):
|
| 402 |
+
model_data = {}
|
| 403 |
+
for model, path in model_paths.items():
|
| 404 |
+
with open(path, encoding="utf-8") as f:
|
| 405 |
+
rows = [json.loads(line) for line in f if line.strip()]
|
| 406 |
+
model_data[model] = {cand_key(row): row for row in rows}
|
| 407 |
+
if len(model_data[model]) != len(rows):
|
| 408 |
+
raise ValueError(f"Duplicate model votes: {model}")
|
| 409 |
+
keys = set(model_data["ds"])
|
| 410 |
+
if any(set(rows) != keys for rows in model_data.values()):
|
| 411 |
+
raise ValueError("三个模型的 pair 集合必须一致,不能丢弃缺票样本")
|
| 412 |
+
disagree_items = []
|
| 413 |
+
with open(merged_path, "w", encoding="utf-8") as f:
|
| 414 |
+
for key in sorted(keys):
|
| 415 |
+
records = {model: rows[key] for model, rows in model_data.items()}
|
| 416 |
+
votes = {model: row["grade"] for model, row in records.items()}
|
| 417 |
+
status, grade = merge_votes(votes)
|
| 418 |
+
row = records["ds"]
|
| 419 |
+
out = {field: row[field] for field in [
|
| 420 |
+
"idx", "item_id", "question", "content", "intent", "title",
|
| 421 |
+
"treecate_full_path", "product_caption"]}
|
| 422 |
+
out.update(retrieved_by=row.get("retrieved_by", []), votes=votes,
|
| 423 |
+
status=status, final_grade=grade)
|
| 424 |
+
for model, record in records.items():
|
| 425 |
+
out[f"{model}_grade"] = record["grade"]
|
| 426 |
+
out[f"{model}_reason"] = record.get("reason", "")
|
| 427 |
+
f.write(json.dumps(out, ensure_ascii=False) + "\n")
|
| 428 |
+
if status == "disagree":
|
| 429 |
+
disagree_items.append(out)
|
| 430 |
+
return merged_path, disagree_items
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def build_judge_prompt(item):
|
| 434 |
+
return SONNET_JUDGE_PROMPT.format(
|
| 435 |
+
question=item["question"],
|
| 436 |
+
content=item.get("content", ""),
|
| 437 |
+
intent=item.get("intent", ""),
|
| 438 |
+
title=item.get("title", ""),
|
| 439 |
+
product_caption=item.get("product_caption", ""),
|
| 440 |
+
category=item.get("treecate_full_path", ""),
|
| 441 |
+
name_a=MODEL_NAMES["ds"],
|
| 442 |
+
grade_a=item.get("ds_grade", ""),
|
| 443 |
+
reason_a=item.get("ds_reason", ""),
|
| 444 |
+
name_b=MODEL_NAMES["qw"],
|
| 445 |
+
grade_b=item.get("qw_grade", ""),
|
| 446 |
+
reason_b=item.get("qw_reason", ""),
|
| 447 |
+
name_c=MODEL_NAMES["glm"],
|
| 448 |
+
grade_c=item.get("glm_grade", ""),
|
| 449 |
+
reason_c=item.get("glm_reason", ""),
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def run_judge(judge_path, disagree_items, args):
|
| 454 |
+
done = load_done(judge_path)
|
| 455 |
+
|
| 456 |
+
def process_one(item):
|
| 457 |
+
raw, error = call_claude_with_retry(
|
| 458 |
+
build_judge_prompt(item), "claude-sonnet-4-6", args.max_retries, args.timeout)
|
| 459 |
+
if error:
|
| 460 |
+
raise RuntimeError(f"{cand_key(item)}: {error}")
|
| 461 |
+
append_jsonl(judge_path, {"idx": item["idx"], "item_id": item["item_id"],
|
| 462 |
+
"votes": item["votes"], **parse_result(raw), "raw_response": raw})
|
| 463 |
+
|
| 464 |
+
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
| 465 |
+
futures = [pool.submit(process_one, item) for item in disagree_items if cand_key(item) not in done]
|
| 466 |
+
for future in as_completed(futures):
|
| 467 |
+
future.result()
|
| 468 |
+
return judge_path
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def final_merge(merged_path, judge_path, final_path):
|
| 472 |
+
judge_results = {}
|
| 473 |
+
if judge_path.exists():
|
| 474 |
+
with open(judge_path, encoding="utf-8") as f:
|
| 475 |
+
for line in f:
|
| 476 |
+
if line.strip():
|
| 477 |
+
row = json.loads(line)
|
| 478 |
+
judge_results[cand_key(row)] = row["grade"]
|
| 479 |
+
with open(merged_path, encoding="utf-8") as fin:
|
| 480 |
+
rows = [json.loads(line) for line in fin if line.strip()]
|
| 481 |
+
for row in rows:
|
| 482 |
+
grade = row["final_grade"] if row["status"] == "agree" else judge_results.get(cand_key(row))
|
| 483 |
+
if grade not in VALID_GRADES:
|
| 484 |
+
raise ValueError(f"Missing or invalid adjudication: {cand_key(row)}")
|
| 485 |
+
with open(final_path, "w", encoding="utf-8") as fout:
|
| 486 |
+
for row in rows:
|
| 487 |
+
if row["status"] == "agree":
|
| 488 |
+
grade, source = row["final_grade"], "model_consensus"
|
| 489 |
+
else:
|
| 490 |
+
grade = judge_results.get(cand_key(row))
|
| 491 |
+
source = "sonnet_judge" if grade else "unresolved"
|
| 492 |
+
out = {"idx": row["idx"], "item_id": row["item_id"],
|
| 493 |
+
"retrieved_by": row["retrieved_by"], "final_grade": grade, "source": source}
|
| 494 |
+
fout.write(json.dumps(out, ensure_ascii=False) + "\n")
|
| 495 |
+
return final_path
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def run_adjudication(args):
|
| 499 |
+
out = Path(args.output_dir)
|
| 500 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 501 |
+
merged, disagree = do_merge({"ds": args.ds, "qw": args.qw, "glm": args.glm}, out / "merged.jsonl")
|
| 502 |
+
judged = run_judge(out / "judged.jsonl", disagree, args)
|
| 503 |
+
final_merge(merged, judged, out / "final.jsonl")
|
| 504 |
+
log(f"合并完成;需裁决 {len(disagree)} 条,输出 {out / 'final.jsonl'}")
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def main():
|
| 508 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 509 |
+
sub = p.add_subparsers(dest="stage", required=True)
|
| 510 |
+
for stage in ("coarse", "fine", "adjudicate"):
|
| 511 |
+
command = sub.add_parser(stage)
|
| 512 |
+
if stage == "adjudicate":
|
| 513 |
+
for name in ("ds", "qw", "glm"):
|
| 514 |
+
command.add_argument(f"--{name}", required=True)
|
| 515 |
+
command.add_argument("--output-dir", required=True)
|
| 516 |
+
else:
|
| 517 |
+
for name in ("input", "queries", "corpus", "output"):
|
| 518 |
+
command.add_argument(f"--{name}", required=True)
|
| 519 |
+
if stage == "coarse":
|
| 520 |
+
command.add_argument("--model-path", required=True)
|
| 521 |
+
else:
|
| 522 |
+
command.add_argument("--concurrency", type=int, default=8)
|
| 523 |
+
command.add_argument("--max-retries", type=int, default=3)
|
| 524 |
+
command.add_argument("--timeout", type=int, default=120)
|
| 525 |
+
if stage == "fine":
|
| 526 |
+
command.add_argument("--captions", required=True)
|
| 527 |
+
command.add_argument("--model", required=True, choices=list(MODEL_NAMES.values()))
|
| 528 |
+
args = p.parse_args()
|
| 529 |
+
{"coarse": run_coarse, "fine": run_fine, "adjudicate": run_adjudication}[args.stage](args)
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
if __name__ == "__main__":
|
| 533 |
+
main()
|
construction/generate_terms.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Qwen3.6-27B 两轮商品词生成:枚举 → 反思;共用一个 vLLM 模型。"""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from utils import append_result, extract_keywords, load_done_idx, RESULTS_DIR
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
TEMPLATE_R1 = '''用户发来一张图片并提出问题,想买商品解决它。你会看到四部分信息(按重要性排序):
|
| 10 |
+
- 用户意图:强力模型结合图文分析后得出的需求判断,比较清晰可靠,是你理解需求的主要依据。
|
| 11 |
+
- 图片内容:客观描述了用户拍的东西,是确定的事实锚点,用来防止跑偏。
|
| 12 |
+
- 用户提问:用户的原始口语提问,可能模糊简略,作为参考。
|
| 13 |
+
- 选品注意:对需求的补充分析,仅供参考,不要被它过度约束。
|
| 14 |
+
|
| 15 |
+
你的任务是推荐淘宝搜索关键词。
|
| 16 |
+
|
| 17 |
+
先想:解决这个需求,有哪几类不同商品能帮上忙?沿下面几个角度过一遍
|
| 18 |
+
(这些角度覆盖了"用户与商品的不同关系",不必每个角度都有商品,但要都想一下):
|
| 19 |
+
- 专用品:为这个需求量身设计的最直接商品
|
| 20 |
+
- 通用替代品:没有专用品时,能顶替使用的通用商品
|
| 21 |
+
- 配套品:用户已有主体物,需要补充的配件 / 耗材 / 替换件
|
| 22 |
+
- 前置品:解决这个需求前,用户可能需要先具备的东西(这一类最容易被忽略,务必想一下:动手之前还缺什么?)
|
| 23 |
+
|
| 24 |
+
再写关键词,要求:
|
| 25 |
+
|
| 26 |
+
1. 必须是淘宝能直接买到的实物,不要土办法或家里的现成物。比如母乳、土、旧牙刷这类不算商品。
|
| 27 |
+
2. 有几种不同解法就给几个词,通常 2~5 个,**至少给一个词,最多不超过 7 个**。同一种商品只保留一个词,不要用不同说法重复描述同一种商品来凑数量。如果这个需求本身只有一种解法,给 1~2 个词就够,不必凑满。
|
| 28 |
+
例如"小白鞋清洗剂""小白鞋清洁液""白色运动鞋去污剂""白色运动鞋清洗泡沫"搜出来是同一类商品,只保留一个即可;"小白鞋清洗剂""洗衣液""肥皂"这些是不同类商品,可以都保留。
|
| 29 |
+
3. 用词要像真人在淘宝搜索框里输入的那样简洁,不要堆砌营销长尾词。例如写"小白鞋清洁液"即可,不要写成"白鞋白鞋清洗清洗剂清洁神器一擦一擦白去污清洁剂专用"。
|
| 30 |
+
4. 用词精准,能指向具体商品,不要用过泛的大类词。例如清洁瓷砖缝隙应写"瓷砖缝隙除垢剂",而不是笼统的"清洁剂"。
|
| 31 |
+
5. 以用户意图为主来判断该推荐什么商品,用图片内容作为事实锚点防止跑偏;选品注意仅供参考,不要被它过度约束。
|
| 32 |
+
6. 结合图片内容一起判断:如果图里的物品还有其他解决方式,也要补上对应关键词。只补图里确实能看出的解法,不要凭空猜测。
|
| 33 |
+
|
| 34 |
+
示例 1:
|
| 35 |
+
用户意图:寻找清洗白色帆布运动鞋(小白鞋)的洗鞋剂或清洁用品
|
| 36 |
+
图片内容:白色帆布运动鞋
|
| 37 |
+
用户提问:脏了用什么洗比较好
|
| 38 |
+
选品注意:帆布材质适合用专用白鞋清洁剂或小白鞋去污膏,需避免使用强力漂白剂以防帆布泛黄损伤;鞋边毛边为设计细节,清洗时应避免大力搓刷以防毛边过度脱散变形
|
| 39 |
+
关键词:["小白鞋清洗剂", "小白鞋去污膏", "软毛洗鞋刷", "洗衣皂", "洗衣液"]
|
| 40 |
+
|
| 41 |
+
示例 2:
|
| 42 |
+
用户意图:寻找菜刀的除锈清洗及日常保养用品(如除锈产品、食用级保养油等)
|
| 43 |
+
图片内容:一把生锈的菜刀
|
| 44 |
+
用户提问:生锈了怎么办
|
| 45 |
+
选品注意:铲柄锈蚀严重,需选用食品安全级别的除锈产品(不可用工业除锈剂);铲面清洗后建议涂抹食用油进行开锅养护防锈,所用保养油须为食用油或食品级护理油
|
| 46 |
+
关键词:["食品级除锈剂", "食品级护理油", "磨刀石"]
|
| 47 |
+
|
| 48 |
+
示例 3:
|
| 49 |
+
用户意图:寻找适合泳镜使用的防雾剂,解决泳镜起雾问题
|
| 50 |
+
图片内容:游泳护目镜(泳镜)
|
| 51 |
+
用户提问:老是起雾怎么办
|
| 52 |
+
选品注意:泳镜镜片通常有防雾涂层,需选择专为泳镜设计的防雾剂(如泳镜专用防雾喷雾或防雾液),避免使用汽车玻璃或普通眼镜用的防雾产品,否则可能损伤镜片原有防雾涂层
|
| 53 |
+
关键词:["泳镜防雾剂", "泳镜防雾液", "泳镜防雾湿巾"]
|
| 54 |
+
|
| 55 |
+
以下是本次需要处理的输入:
|
| 56 |
+
|
| 57 |
+
用户意图:{intent}
|
| 58 |
+
图片内容:{content}
|
| 59 |
+
用户提问:{query}
|
| 60 |
+
选品注意:{note}
|
| 61 |
+
|
| 62 |
+
直接输出 JSON 列表,不要输出其他内容。'''
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
TEMPLATE_R2 = '''用户发来一张图片并提出问题,想买商品解决它。你之前已经推荐了一批淘宝搜索关键词,现在要复查一遍,重点是查漏补缺,输出最终列表。
|
| 66 |
+
|
| 67 |
+
先回顾这次需求的原始信息(按重要性排序):
|
| 68 |
+
- 用户意图:这是强力模型结合图文分析后得出的需求判断,比较清晰可靠,是你理解需求的主要依据。
|
| 69 |
+
- 图片内容:客观描述了用户拍的东西,是确定的事实锚点,用来防止跑偏。
|
| 70 |
+
- 用户提问:用户的原始口语提问,可能模糊简略,作为参考。
|
| 71 |
+
- 选品注意:对需求的补充分析,仅供参考,不要被它过度约束。
|
| 72 |
+
|
| 73 |
+
请执行以下检查,然后给出最终关键词列表:
|
| 74 |
+
|
| 75 |
+
■ 检查1(查漏补缺,最重要):对照"专用品 / 通用替代品 / 配套品 / 前置品"四个角度,再过一遍是否有遗漏。
|
| 76 |
+
重点复查【配套品】和【前置品】——它们最常被漏:
|
| 77 |
+
- 配套品:用户已有的主体物,是否需要补充配件、耗材或替换件?
|
| 78 |
+
- 前置品:用户满足这个需求之前,是否还缺某个前置物品?
|
| 79 |
+
补充时优先补"新的解法",不必刻意补与已有词只是材质、款式不同的同类商品(如已有"耳机架",不必再单列"木质耳机架""金属耳机架")。
|
| 80 |
+
只补图片和需求里确实能看出的解法,不要凭空猜测。
|
| 81 |
+
|
| 82 |
+
■ 检查2(防重复):现有关键词里,有没有搜出来其实是同一类商品的?
|
| 83 |
+
例如"小白鞋清洗剂"和"白鞋去污液"搜出来是同一类商品,应合并成一个;
|
| 84 |
+
而"小白鞋清洗剂"和"洗衣液"是不同类商品,应都保留。
|
| 85 |
+
如有重复,合并即可。
|
| 86 |
+
|
| 87 |
+
■ 检查3(防跑偏,仅处理明显问题):
|
| 88 |
+
- 是否有关键词只是字面相关,买来其实完全解决不了需求?→ 删掉
|
| 89 |
+
- 是否有关键词太宽泛、无法指向具体商品(如"清洁剂")?→ 细化为精准词(如"瓷砖缝隙除垢剂")
|
| 90 |
+
注意:不确定的不要删,后续流程会兜底。宁可多给,不要漏给。
|
| 91 |
+
|
| 92 |
+
修订原则:
|
| 93 |
+
- 以补充为主,不要轻易删除上一轮的关键词。
|
| 94 |
+
- 若某个需求本身解法就很有限,不必为凑数强行发散,自然覆盖到即可。
|
| 95 |
+
- 关键词总数最多不超过 7 个。如果补充后超过 7 个,优先保留最能解决需求的词,合并或去掉冗余的、最弱的。
|
| 96 |
+
- 每个关键词都必须是淘宝能直接买到的实物。
|
| 97 |
+
- 用词简洁,像真人在搜索框输入的那样,不要堆砌长尾词。
|
| 98 |
+
|
| 99 |
+
示例:
|
| 100 |
+
用户意图:寻找清洗白色帆布运动鞋(小白鞋)的洗鞋剂或清洁用品
|
| 101 |
+
图片内容:白色帆布运动鞋
|
| 102 |
+
用户提问:脏了用什么洗比较好
|
| 103 |
+
选品注意:帆布材质适合用专用白鞋清洁剂或小白鞋去污膏,需避免使用强力漂白剂以防帆布泛黄损伤
|
| 104 |
+
上一轮关键词:["小白鞋清洗剂", "小白鞋清洗液", "白鞋去污膏", "洗衣液"]
|
| 105 |
+
复查过程:
|
| 106 |
+
- 检查1:配套品角度——洗鞋需要刷子,补"软毛洗鞋刷";通用替代品角度——洗衣皂也能洗鞋,补"洗衣皂";前置品角度——洗后防泛黄可用"补色/防氧化"类,但图片和需求看不出明确需要,不凭空补。
|
| 107 |
+
- 检查2:"小白鞋清洗剂"和"小白鞋清洗液"搜出来是同一类商品,合并为"小白鞋清洗剂";"白鞋去污膏"和"洗衣液"是不同解法,保留。
|
| 108 |
+
- 检查3:无字面相关或过泛的词,不删。
|
| 109 |
+
最终关键词:["小白鞋清洗剂", "白鞋去污膏", "洗衣液", "软毛洗鞋刷", "洗衣皂"]
|
| 110 |
+
|
| 111 |
+
以下是本次需要处理的输入:
|
| 112 |
+
|
| 113 |
+
用户意图:{intent}
|
| 114 |
+
图片内容:{content}
|
| 115 |
+
用户提问:{query}
|
| 116 |
+
选品注意:{note}
|
| 117 |
+
|
| 118 |
+
你上一轮给出的关键词:
|
| 119 |
+
{first_round_keywords}
|
| 120 |
+
|
| 121 |
+
只输出最终 JSON 列表,不要输出其他内容。'''
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
R1_OUT_NAME = "terms_r1"
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
R2_OUT_NAME = "terms_r2"
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
R1_PIPELINE = "enumeration"
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
R2_PIPELINE = "reflection"
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
CHUNK_SIZE = 512
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
MAX_NEW_TOKENS = 512
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
DEFAULT_MODEL_PATH = str(Path.home() / "models" / "Qwen" / "Qwen3.6-27B")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def load_input(path):
|
| 146 |
+
with open(path, encoding="utf-8") as f:
|
| 147 |
+
rows = [json.loads(line) for line in f if line.strip()]
|
| 148 |
+
return {str(row["idx"]): dict(row, idx=str(row["idx"])) for row in rows}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _sort_key(idx):
|
| 152 |
+
return (0, int(idx)) if str(idx).isdigit() else (1, str(idx))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def load_r1_results(out_dir=None):
|
| 156 |
+
base = Path(out_dir) if out_dir is not None else RESULTS_DIR
|
| 157 |
+
path = base / f"{R1_OUT_NAME}.jsonl"
|
| 158 |
+
results = {}
|
| 159 |
+
if path.exists():
|
| 160 |
+
with open(path, encoding="utf-8") as f:
|
| 161 |
+
for line in f:
|
| 162 |
+
line = line.strip()
|
| 163 |
+
if line:
|
| 164 |
+
try:
|
| 165 |
+
d = json.loads(line)
|
| 166 |
+
results[d["idx"]] = d
|
| 167 |
+
except (json.JSONDecodeError, KeyError):
|
| 168 |
+
continue
|
| 169 |
+
return results
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def generate_batch(llm, prompts):
|
| 173 |
+
from vllm import SamplingParams
|
| 174 |
+
tokenizer = llm.get_tokenizer()
|
| 175 |
+
inputs = [tokenizer.apply_chat_template(
|
| 176 |
+
[{"role": "user", "content": prompt}], tokenize=False,
|
| 177 |
+
add_generation_prompt=True, enable_thinking=False) for prompt in prompts]
|
| 178 |
+
outputs = llm.generate(inputs, SamplingParams(max_tokens=MAX_NEW_TOKENS, temperature=0.0))
|
| 179 |
+
if len(outputs) != len(prompts):
|
| 180 |
+
raise ValueError("vLLM output count does not match input count")
|
| 181 |
+
return [output.outputs[0].text.strip() for output in outputs]
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def run_round(llm, items, template, out_name, pipeline, done_idx,
|
| 185 |
+
r1_results=None, out_dir=None):
|
| 186 |
+
pending = [(idx, row) for idx, row in items if idx not in done_idx
|
| 187 |
+
and (r1_results is None or idx in r1_results)]
|
| 188 |
+
for start in range(0, len(pending), CHUNK_SIZE):
|
| 189 |
+
chunk = pending[start:start + CHUNK_SIZE]
|
| 190 |
+
prompts = []
|
| 191 |
+
for idx, row in chunk:
|
| 192 |
+
fields = dict(row["scene"], query=row["query"])
|
| 193 |
+
if r1_results is not None:
|
| 194 |
+
fields["first_round_keywords"] = json.dumps(
|
| 195 |
+
r1_results[idx]["product_keywords"], ensure_ascii=False)
|
| 196 |
+
prompts.append(template.format(**fields))
|
| 197 |
+
responses = generate_batch(llm, prompts)
|
| 198 |
+
for (idx, row), raw in zip(chunk, responses):
|
| 199 |
+
result = {"idx": idx, "query": row["query"], "image_url": row["image_url"],
|
| 200 |
+
"scene": row["scene"], "pipeline": pipeline,
|
| 201 |
+
"product_keywords": list(dict.fromkeys(k.strip() for k in extract_keywords(raw) if k.strip()))[:7], "raw_response": raw}
|
| 202 |
+
if r1_results is not None:
|
| 203 |
+
result["r1_keywords"] = r1_results[idx]["product_keywords"]
|
| 204 |
+
append_result(result, out_name, out_dir=out_dir)
|
| 205 |
+
done_idx.add(idx)
|
| 206 |
+
print(f"{pipeline}:新增 {len(pending)} 条")
|
| 207 |
+
return len(pending)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def main():
|
| 211 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 212 |
+
p.add_argument("--input", required=True, help="JSONL: idx, query, image_url, scene")
|
| 213 |
+
p.add_argument("--out-dir", required=True)
|
| 214 |
+
p.add_argument("--model-path", default=DEFAULT_MODEL_PATH)
|
| 215 |
+
args = p.parse_args()
|
| 216 |
+
from vllm import LLM
|
| 217 |
+
llm = LLM(model=args.model_path, trust_remote_code=True, dtype="bfloat16")
|
| 218 |
+
items = sorted(load_input(args.input).items(), key=lambda kv: _sort_key(kv[0]))
|
| 219 |
+
run_round(llm, items, TEMPLATE_R1, R1_OUT_NAME, R1_PIPELINE,
|
| 220 |
+
load_done_idx(R1_OUT_NAME, out_dir=args.out_dir), out_dir=args.out_dir)
|
| 221 |
+
run_round(llm, items, TEMPLATE_R2, R2_OUT_NAME, R2_PIPELINE,
|
| 222 |
+
load_done_idx(R2_OUT_NAME, out_dir=args.out_dir),
|
| 223 |
+
r1_results=load_r1_results(args.out_dir), out_dir=args.out_dir)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
main()
|
construction/intent_analysis.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""图片与原始 query → scene(content、intent、note);使用原始 Claude CLI prompt。"""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import subprocess
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 11 |
+
|
| 12 |
+
STAGE1_PROMPT = """请观察图片并结合用户的问题,以 JSON 格式回答以下三点:
|
| 13 |
+
|
| 14 |
+
1. "content":图中是什么东西或什么场景?如果物品的具体类型会影响解决方案,请说清楚(例如螺丝是内六角还是十字的,因为这决定需要什么工具)。若某个关键特征看不清或不确定,明确写出"疑似"或"无法确定",不要臆断。
|
| 15 |
+
2. "intent":结合图片和提问,用户想解决什么问题?尽量往搜索商品上靠(如"寻找清洗白色运动鞋的用品");但如果靠不上(比如用户只是想了解、评价、比较、询问某属性),就别硬靠,直接输出原始意图,如"想了解这款衣服的评价如何"。
|
| 16 |
+
3. "note":根据识别出的物品/场景和用户意图,指出一句解决该问题时的注意事项,重点是会影响"该选什么商品"的地方。如果没有特别需要注意的,就留空 ""。
|
| 17 |
+
|
| 18 |
+
示例:
|
| 19 |
+
- 菜刀图 + "生锈了怎么处理" →
|
| 20 |
+
{"content": "菜刀,刀面有锈斑", "intent": "寻找给菜刀除锈的工具或用品", "note": "菜刀直接接触食物,除锈处理需满足食品安全要求,不能用工业除锈剂"}
|
| 21 |
+
- 内六角螺丝图 + "怎么拧下来" →
|
| 22 |
+
{"content": "内六角螺丝", "intent": "寻找拧下内六角螺丝的工具", "note": "内六角螺丝需要特定规格的工具,规格不匹配无法使用"}
|
| 23 |
+
- 免打孔挂杆图 + "厨房墙上挂东西用啥" →
|
| 24 |
+
{"content": "厨房墙面收纳挂杆", "intent": "寻找厨房墙面免打孔收纳挂杆", "note": "需免打孔安装;厨房环境需考虑承重和防油污"}
|
| 25 |
+
- 针织衫图 + "这种容易起球吗" →
|
| 26 |
+
{"content": "针织上衣", "intent": "想了解这款衣服是否容易起球", "note": ""}
|
| 27 |
+
|
| 28 |
+
请直接输出 JSON 对象,不要输出任何其他内容。"""
|
| 29 |
+
|
| 30 |
+
SYSTEM_PROMPT = "你是一个多模态场景分析助手。用户会提供一张图片的文件路径和一个搜索查询。请先用 Read 工具读取图片,然后根据图片内容和查询回答。只输出 JSON 对象,不要输出任何解释或其他内容。"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def load_input_jsonl(path):
|
| 34 |
+
with open(path, encoding="utf-8") as f:
|
| 35 |
+
rows = [json.loads(line) for line in f if line.strip()]
|
| 36 |
+
return [dict(row, idx=str(row["idx"])) for row in rows]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_done_jsonl(path):
|
| 40 |
+
done = set()
|
| 41 |
+
if os.path.exists(path):
|
| 42 |
+
with open(path, encoding="utf-8") as f:
|
| 43 |
+
for line in f:
|
| 44 |
+
line = line.strip()
|
| 45 |
+
if not line:
|
| 46 |
+
continue
|
| 47 |
+
try:
|
| 48 |
+
done.add(str(json.loads(line)["idx"]))
|
| 49 |
+
except (json.JSONDecodeError, KeyError):
|
| 50 |
+
continue
|
| 51 |
+
return done
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
_write_lock = threading.Lock()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def append_jsonl(path, obj):
|
| 58 |
+
with _write_lock:
|
| 59 |
+
with open(path, "a", encoding="utf-8") as f:
|
| 60 |
+
f.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
| 61 |
+
f.flush()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def extract_json_obj(text):
|
| 65 |
+
import re
|
| 66 |
+
try:
|
| 67 |
+
match = re.search(r"\{.*\}", text, re.DOTALL)
|
| 68 |
+
if match:
|
| 69 |
+
parsed = json.loads(match.group())
|
| 70 |
+
if isinstance(parsed, dict):
|
| 71 |
+
return parsed
|
| 72 |
+
except (json.JSONDecodeError, ValueError):
|
| 73 |
+
pass
|
| 74 |
+
return {"content": "未知", "intent": "未知", "note": "未知", "_raw": text}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def call_claude(image_path, query, model, timeout_seconds):
|
| 78 |
+
user_prompt = f"请先用 Read 工具读取这张图片: {image_path}\n\n用户搜索查询:{query}\n\n{STAGE1_PROMPT}"
|
| 79 |
+
|
| 80 |
+
result = subprocess.run(
|
| 81 |
+
[
|
| 82 |
+
"claude", "-p", user_prompt,
|
| 83 |
+
"--system-prompt", SYSTEM_PROMPT,
|
| 84 |
+
"--model", model,
|
| 85 |
+
"--output-format", "text",
|
| 86 |
+
"--allowedTools", "Read",
|
| 87 |
+
"--no-session-persistence",
|
| 88 |
+
"--bare",
|
| 89 |
+
],
|
| 90 |
+
stdin=subprocess.DEVNULL,
|
| 91 |
+
capture_output=True,
|
| 92 |
+
text=True,
|
| 93 |
+
timeout=timeout_seconds,
|
| 94 |
+
)
|
| 95 |
+
if result.returncode != 0:
|
| 96 |
+
stderr = (result.stderr or "").strip()
|
| 97 |
+
raise RuntimeError(f"claude -p exit {result.returncode}: {stderr}")
|
| 98 |
+
|
| 99 |
+
return result.stdout.strip()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def call_claude_with_retry(image_path, query, model, max_retries, timeout_seconds):
|
| 103 |
+
for attempt in range(1, max_retries + 1):
|
| 104 |
+
try:
|
| 105 |
+
raw = call_claude(image_path, query, model, timeout_seconds)
|
| 106 |
+
return raw, None
|
| 107 |
+
except Exception as exc:
|
| 108 |
+
if attempt == max_retries:
|
| 109 |
+
return None, str(exc)
|
| 110 |
+
time.sleep(min(2 ** attempt, 10))
|
| 111 |
+
return None, "max retries exceeded"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def run_stage1(args):
|
| 115 |
+
rows = load_input_jsonl(args.input)
|
| 116 |
+
done = load_done_jsonl(args.output)
|
| 117 |
+
os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
|
| 118 |
+
|
| 119 |
+
def process_one(row):
|
| 120 |
+
image_path = os.path.abspath(os.path.join(args.image_dir, row["image_url"]))
|
| 121 |
+
if not os.path.isfile(image_path):
|
| 122 |
+
raise FileNotFoundError(image_path)
|
| 123 |
+
raw, error = call_claude_with_retry(
|
| 124 |
+
image_path, row["query"], args.model, args.max_retries, args.timeout)
|
| 125 |
+
if error:
|
| 126 |
+
raise RuntimeError(f"idx={row['idx']}: {error}")
|
| 127 |
+
append_jsonl(args.output, {
|
| 128 |
+
**row, "scene": extract_json_obj(raw), "raw_response_s1": raw,
|
| 129 |
+
})
|
| 130 |
+
|
| 131 |
+
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
| 132 |
+
futures = [pool.submit(process_one, row) for row in rows if row["idx"] not in done]
|
| 133 |
+
for future in as_completed(futures):
|
| 134 |
+
future.result()
|
| 135 |
+
print(f"意图分析完成:{args.output}")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def main():
|
| 139 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 140 |
+
p.add_argument("--input", required=True, help="JSONL: idx, query, image_url(本地图片文件名)")
|
| 141 |
+
p.add_argument("--output", required=True)
|
| 142 |
+
p.add_argument("--image-dir", required=True)
|
| 143 |
+
p.add_argument("--model", default="claude-sonnet-4-6")
|
| 144 |
+
p.add_argument("--concurrency", type=int, default=8)
|
| 145 |
+
p.add_argument("--max-retries", type=int, default=3)
|
| 146 |
+
p.add_argument("--timeout", type=int, default=120)
|
| 147 |
+
run_stage1(p.parse_args())
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
main()
|
construction/pooling.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Pool top-20 runs, annotate unseen pairs, and export complete five-way qrels."""
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from utils import GRADE_ALIASES, index_pairs, pair_key, read_jsonl, read_pairs, write_jsonl
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def build_pool(recall_path, run_paths, output_path, top_k=20):
|
| 12 |
+
if top_k < 1 or not run_paths:
|
| 13 |
+
raise ValueError("Supply retrieval runs and a positive top_k")
|
| 14 |
+
pairs = {}
|
| 15 |
+
for row in read_pairs(recall_path):
|
| 16 |
+
key = pair_key(row)
|
| 17 |
+
pairs.setdefault(key, set()).update(row.get("retrieved_by", []))
|
| 18 |
+
query_ids = {qid for qid, _ in pairs}
|
| 19 |
+
if not query_ids:
|
| 20 |
+
raise ValueError("Initial candidate pool is empty")
|
| 21 |
+
for path in run_paths:
|
| 22 |
+
with open(path, encoding="utf-8") as f:
|
| 23 |
+
run = json.load(f)
|
| 24 |
+
qids = [str(row["qid"]) for row in run]
|
| 25 |
+
if len(set(qids)) != len(qids) or set(qids) != query_ids:
|
| 26 |
+
raise ValueError(f"Run query IDs must match initial pool exactly: {path}")
|
| 27 |
+
source = f"model:{Path(path).parent.name}/{Path(path).name}"
|
| 28 |
+
for row in run:
|
| 29 |
+
hits = row["ranked"][:top_k]
|
| 30 |
+
ids = [str(hit["did"]) for hit in hits]
|
| 31 |
+
if len(ids) < top_k or len(set(ids)) != len(ids):
|
| 32 |
+
raise ValueError(f"Run needs {top_k} unique products per query: {path}, {row['qid']}")
|
| 33 |
+
for did in ids:
|
| 34 |
+
pairs.setdefault((str(row["qid"]), did), set()).add(source)
|
| 35 |
+
rows = [{"idx": qid, "item_id": did, "retrieved_by": sorted(sources)}
|
| 36 |
+
for (qid, did), sources in sorted(pairs.items())]
|
| 37 |
+
write_jsonl(output_path, rows)
|
| 38 |
+
return rows
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def coarse_index(paths):
|
| 42 |
+
rows = index_pairs([row for path in paths for row in read_pairs(path)])
|
| 43 |
+
for row in rows.values():
|
| 44 |
+
if row.get("decision") not in {"keep", "discard"}:
|
| 45 |
+
raise ValueError(f"Invalid coarse decision: {pair_key(row)}")
|
| 46 |
+
return rows
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def prepare_coarse(merged_path, coarse_path, output_path, todo_path):
|
| 50 |
+
pool = index_pairs(read_pairs(merged_path))
|
| 51 |
+
coarse = coarse_index([coarse_path])
|
| 52 |
+
if set(coarse) - set(pool):
|
| 53 |
+
raise ValueError("Existing coarse results contain pairs outside the pool")
|
| 54 |
+
done, todo = [], []
|
| 55 |
+
for key, row in pool.items():
|
| 56 |
+
if key in coarse:
|
| 57 |
+
done.append({**row, "decision": coarse[key]["decision"],
|
| 58 |
+
"reason": coarse[key].get("reason", "")})
|
| 59 |
+
else:
|
| 60 |
+
todo.append(row)
|
| 61 |
+
write_jsonl(output_path, done)
|
| 62 |
+
write_jsonl(todo_path, todo)
|
| 63 |
+
return done, todo
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def merge_coarse(merged_path, result_paths, output_path):
|
| 67 |
+
pool = index_pairs(read_pairs(merged_path))
|
| 68 |
+
results = coarse_index(result_paths)
|
| 69 |
+
if set(pool) != set(results):
|
| 70 |
+
raise ValueError(f"Incomplete coarse results: missing={len(set(pool)-set(results))}, "
|
| 71 |
+
f"extra={len(set(results)-set(pool))}")
|
| 72 |
+
rows = [{**row, "decision": results[key]["decision"],
|
| 73 |
+
"reason": results[key].get("reason", "")} for key, row in pool.items()]
|
| 74 |
+
write_jsonl(output_path, rows)
|
| 75 |
+
return rows
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def finalize(pool_path, coarse_paths, fine_paths, queries_path, output_dir):
|
| 79 |
+
"""Require complete labels; filter queries only after initial and pooled labeling."""
|
| 80 |
+
pool = index_pairs(read_pairs(pool_path))
|
| 81 |
+
coarse = coarse_index(coarse_paths)
|
| 82 |
+
fine = index_pairs([row for path in fine_paths for row in read_pairs(path)])
|
| 83 |
+
if set(coarse) != set(pool):
|
| 84 |
+
raise ValueError("Coarse results must cover exactly the complete pool")
|
| 85 |
+
kept_pairs = {key for key, row in coarse.items() if row["decision"] == "keep"}
|
| 86 |
+
if set(fine) != kept_pairs:
|
| 87 |
+
raise ValueError(f"Fine results must cover all and only coarse-kept pairs: "
|
| 88 |
+
f"missing={len(kept_pairs-set(fine))}, extra={len(set(fine)-kept_pairs)}")
|
| 89 |
+
queries = read_jsonl(queries_path)
|
| 90 |
+
qids = [str(row["idx"]) for row in queries]
|
| 91 |
+
if len(set(qids)) != len(qids) or set(qids) != {qid for qid, _ in pool}:
|
| 92 |
+
raise ValueError("Query IDs must match the complete pool exactly")
|
| 93 |
+
judgments = defaultdict(list)
|
| 94 |
+
membership = []
|
| 95 |
+
for key, pair in pool.items():
|
| 96 |
+
if coarse[key]["decision"] == "discard":
|
| 97 |
+
grade = "N3"
|
| 98 |
+
else:
|
| 99 |
+
raw_grade = fine[key].get("final_grade")
|
| 100 |
+
if not isinstance(raw_grade, str) or raw_grade not in GRADE_ALIASES:
|
| 101 |
+
raise ValueError(f"Missing or invalid final grade: {key}")
|
| 102 |
+
grade = GRADE_ALIASES[raw_grade]
|
| 103 |
+
judgments[key[0]].append({"item_id": key[1], "final_grade": grade})
|
| 104 |
+
membership.append({**pair, "final_grade": grade})
|
| 105 |
+
retained = {qid for qid, items in judgments.items()
|
| 106 |
+
if 1 <= sum(item["final_grade"] == "L1" for item in items) <= 20}
|
| 107 |
+
final_queries = [{"idx": str(row["idx"]), "query": row["query"], "image_url": row["image_url"]}
|
| 108 |
+
for row in queries if str(row["idx"]) in retained]
|
| 109 |
+
out = Path(output_dir)
|
| 110 |
+
# Keep IDs and corpus unchanged; only the final query set is filtered.
|
| 111 |
+
write_jsonl(out / "mipr_query.jsonl", final_queries)
|
| 112 |
+
write_jsonl(out / "mipr_annotation.jsonl", [
|
| 113 |
+
{"idx": qid, "items": judgments[qid]} for qid in qids if qid in retained])
|
| 114 |
+
write_jsonl(out / "pool_membership.jsonl", [row for row in membership if row["idx"] in retained])
|
| 115 |
+
return retained
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def main():
|
| 119 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 120 |
+
sub = p.add_subparsers(dest="command", required=True)
|
| 121 |
+
build = sub.add_parser("build", help="Merge initial flat pairs and model top-20 runs")
|
| 122 |
+
build.add_argument("--recall", required=True)
|
| 123 |
+
build.add_argument("--runs", nargs="+", required=True)
|
| 124 |
+
build.add_argument("--top-k", type=int, default=20)
|
| 125 |
+
build.add_argument("--output", required=True)
|
| 126 |
+
prepare = sub.add_parser("prepare", help="Reuse old coarse results and emit unseen pairs")
|
| 127 |
+
prepare.add_argument("--pool", required=True)
|
| 128 |
+
prepare.add_argument("--coarse", required=True)
|
| 129 |
+
prepare.add_argument("--done", required=True)
|
| 130 |
+
prepare.add_argument("--todo", required=True)
|
| 131 |
+
merge = sub.add_parser("merge", help="Combine reused and newly screened pairs")
|
| 132 |
+
merge.add_argument("--pool", required=True)
|
| 133 |
+
merge.add_argument("--results", nargs="+", required=True)
|
| 134 |
+
merge.add_argument("--output", required=True)
|
| 135 |
+
final = sub.add_parser("finalize", help="Merge all labels, map N1/N2/N3, and filter queries")
|
| 136 |
+
final.add_argument("--pool", required=True)
|
| 137 |
+
final.add_argument("--coarse", nargs="+", required=True)
|
| 138 |
+
final.add_argument("--fine", nargs="+", required=True)
|
| 139 |
+
final.add_argument("--queries", required=True)
|
| 140 |
+
final.add_argument("--output-dir", required=True)
|
| 141 |
+
args = p.parse_args()
|
| 142 |
+
if args.command == "build":
|
| 143 |
+
build_pool(args.recall, args.runs, args.output, args.top_k)
|
| 144 |
+
elif args.command == "prepare":
|
| 145 |
+
prepare_coarse(args.pool, args.coarse, args.done, args.todo)
|
| 146 |
+
elif args.command == "merge":
|
| 147 |
+
merge_coarse(args.pool, args.results, args.output)
|
| 148 |
+
else:
|
| 149 |
+
finalize(args.pool, args.coarse, args.fine, args.queries, args.output_dir)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
if __name__ == "__main__":
|
| 153 |
+
main()
|
construction/query_filter.py
ADDED
|
@@ -0,0 +1,563 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Query 筛选:规则 → 粗筛 → 双模型细筛 → 意图去重。"""
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import subprocess
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
from utils import (deduplicate, load_embeddings, load_model_and_processor,
|
| 14 |
+
read_jsonl, write_jsonl)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# 共用 I/O。
|
| 18 |
+
_write_lock = threading.Lock()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_done(path):
|
| 22 |
+
"""读取已完成的 idx(支持 ok 文件;failed 里的 idx 不算 done,允许重试)。"""
|
| 23 |
+
done = set()
|
| 24 |
+
if not os.path.exists(path):
|
| 25 |
+
return done
|
| 26 |
+
with open(path, encoding="utf-8") as f:
|
| 27 |
+
for line in f:
|
| 28 |
+
line = line.strip()
|
| 29 |
+
if not line:
|
| 30 |
+
continue
|
| 31 |
+
try:
|
| 32 |
+
done.add(str(json.loads(line)["idx"]))
|
| 33 |
+
except Exception:
|
| 34 |
+
continue
|
| 35 |
+
return done
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def append_jsonl(path, obj):
|
| 39 |
+
with _write_lock:
|
| 40 |
+
with open(path, "a", encoding="utf-8") as f:
|
| 41 |
+
f.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
| 42 |
+
f.flush()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def extract_json_obj(text):
|
| 46 |
+
try:
|
| 47 |
+
match = re.search(r"\{.*\}", text, re.DOTALL)
|
| 48 |
+
if match:
|
| 49 |
+
parsed = json.loads(match.group())
|
| 50 |
+
if isinstance(parsed, dict):
|
| 51 |
+
return parsed
|
| 52 |
+
except (json.JSONDecodeError, ValueError):
|
| 53 |
+
pass
|
| 54 |
+
return {}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# 1. 规则筛选。
|
| 58 |
+
EXCLUDE_RULES = [
|
| 59 |
+
# ── 品牌/产品识别 ──
|
| 60 |
+
(r'(是|什么|哪个|哪家).*(品牌|牌子)', '品牌识别'),
|
| 61 |
+
(r'(哪些|推荐|有没有|有.*).*(品牌|牌子)', '品牌推荐'),
|
| 62 |
+
(r'是什么(材质|宝石|面料|系列|风格|成分)', '材质识别'),
|
| 63 |
+
(r'(叫什么|叫啥)', '名称识别'),
|
| 64 |
+
|
| 65 |
+
# ── 材质选择(非识别,答案是材质不是商品)──
|
| 66 |
+
(r'(用|选|买|换).*(什么|哪种).*(材质|材料|面料)', '材质选择'),
|
| 67 |
+
(r'(哪种|什么样的?|什么).*(材质|材料|面料)', '材质选择'),
|
| 68 |
+
|
| 69 |
+
# ── 穿搭搭配(服饰/饰品/鞋帽审美类)──
|
| 70 |
+
(r'(配|搭|穿).*(什么|哪种|哪款|哪个).*'
|
| 71 |
+
r'(衣服|裤子|裙子|外套|鞋子|鞋|内搭|打底|袜子|围巾|包包|帽子|项链|'
|
| 72 |
+
r'戒指|头盔|内衣|手链|耳环|腰带|领带|饰品|发饰|枕套|杯套|'
|
| 73 |
+
r'花边|地毯|桌布|桌旗)', '穿搭搭配'),
|
| 74 |
+
(r'(配|搭配).*(什么|哪种).*'
|
| 75 |
+
r'(茶几|沙发|椅子|灯|窗帘|桌子|柜子|鼠标垫|办公桌|床)', '家居搭配'),
|
| 76 |
+
(r'怎么(搭配|搭|穿).*(好看|显瘦|显高|不臃肿|不单调|不压|显腿长|不显)',
|
| 77 |
+
'穿搭建议'),
|
| 78 |
+
(r'(什么|哪种|哪款).*(比较搭|很搭|更搭|搭$)', '穿搭搭配'),
|
| 79 |
+
(r'(配|搭配).*(什么|哪种).*'
|
| 80 |
+
r'(茶点|饮品|零食|甜品|小吃|饮料|酒)', '食品搭配'),
|
| 81 |
+
(r'.{0,6}(什么|哪种).*(好看|好吃|好喝).*$', '审美主观'),
|
| 82 |
+
|
| 83 |
+
# ── 颜色选择 ──
|
| 84 |
+
(r'(什么|哪个|哪种|选|挑).*颜色', '颜色选择'),
|
| 85 |
+
(r'(还有|其他|别的).*(颜色|色$|主题)', '颜色主题'),
|
| 86 |
+
|
| 87 |
+
# ── 体型/年龄/肤色适合 ──
|
| 88 |
+
(r'适合(什么|哪种).*(身材|体型|脚型|肤色|体质|人穿|人群|身高|发量|肤质)', '体型适合'),
|
| 89 |
+
(r'适合(多大|几岁|什么|哪个).*(年龄|年龄段|岁|孩子|小朋友|宝宝|女宝|男宝)', '年龄适合'),
|
| 90 |
+
(r'多大.*(年龄|岁).*(可以|能|适合)', '年龄适合'),
|
| 91 |
+
(r'(什么|哪种)(身材|体型|肤质|肤色|发量|体质).*(适合|合适)', '体型适合'),
|
| 92 |
+
(r'适合(什么|哪种).*(鞋型|脸型|发型|户型|腿型|手型)', '类型适合'),
|
| 93 |
+
(r'适合.*(什么|哪种|哪些|哪个).*(场合|场景|季节)', '场合适合'),
|
| 94 |
+
(r'适合(多大|多少).*(平米|平方|面积)', '面积适合'),
|
| 95 |
+
(r'适合.*送(给|什么)', '送礼对象'),
|
| 96 |
+
(r'送.*(选|挑|买|推荐).*(哪种|什么|哪个)', '送礼选择'),
|
| 97 |
+
(r'送.*(人|长辈|朋友|领导|客户|同事|老师|父母).*(买|选|推荐|哪种|什么|哪个)', '送礼选择'),
|
| 98 |
+
(r'适合.*(放在|放到|摆在|摆放)', '摆放位置'),
|
| 99 |
+
(r'(放在|放到|摆在).*(哪里|哪儿|什么位置)', '摆放位置'),
|
| 100 |
+
|
| 101 |
+
# ── 价格/定制/性价比 ──
|
| 102 |
+
(r'多少钱|怎么收费|怎么定制|运费险', '价格定制'),
|
| 103 |
+
(r'(平价|便宜|性价比|同价位|低价|高价).*(替代|替换|推荐|平替|款|高的|好的)', '价格比较'),
|
| 104 |
+
(r'(贵不贵|划算|值不值|预算)', '价格咨询'),
|
| 105 |
+
|
| 106 |
+
# ── 找同款/来源 ──
|
| 107 |
+
(r'(同款|去哪|在哪|哪里).*(买|找|配|搜)', '找同款'),
|
| 108 |
+
(r'找源头|上哪买', '找渠道'),
|
| 109 |
+
(r'(博主|模特).*(同款|佩戴|穿)', '找同款'),
|
| 110 |
+
(r'怎么(搜|搜索|找到|搜到)', '找同款'),
|
| 111 |
+
(r'一模一样', '找同款'),
|
| 112 |
+
|
| 113 |
+
# ── 找类似款式 ──
|
| 114 |
+
(r'类似.*(款式|款|风格|的有|还有|有哪些|有没有)', '找类似款'),
|
| 115 |
+
|
| 116 |
+
# ── 尺寸/规格/型号 ──
|
| 117 |
+
(r'(多大|什么|哪种|哪个).*(尺寸|尺码|号码)', '尺寸询问'),
|
| 118 |
+
(r'(适配|兼容|匹配).*(尺寸|型号|规格)', '适配规格'),
|
| 119 |
+
(r'(搭配|配).*(什么|哪个).*(型号|规格)', '适配规格'),
|
| 120 |
+
(r'(买|选|该).*什么.*(型号|规格)', '型号选择'),
|
| 121 |
+
(r'(怎么|如何).*(选|挑|买).*(尺码|尺寸|码数|号)', '尺码选择'),
|
| 122 |
+
(r'(容量|尺寸).*(一般|大概)?(多大|多少)', '规格询问'),
|
| 123 |
+
(r'(多大|多少).*容量', '规格询问'),
|
| 124 |
+
(r'能(装|放|容纳|坐|睡).*多少', '容量询问'),
|
| 125 |
+
(r'多(大码|少瓦|厚|薄|宽|长|高|重)', '规格询问'),
|
| 126 |
+
(r'搭配.*多(厚|薄|宽|长|高|大)', '规格询问'),
|
| 127 |
+
(r'(适合|够).*几(个|口).*(人|口)', '容量规格'),
|
| 128 |
+
(r'(挂|放|装|摆).*几(个|只|盏|盆)', '数量规格'),
|
| 129 |
+
(r'多少(瓦|升|毫升|安|伏|度|克|斤)', '规格询问'),
|
| 130 |
+
(r'能.*(用|跑|玩|撑|续航).*(几|多少).*(个小时|小时|天|分钟|公里)', '续航询问'),
|
| 131 |
+
|
| 132 |
+
# ── 使用寿命/更换周期/质保 ──
|
| 133 |
+
(r'(能用|能放|能保存|能跑|能走|能飞|能开|留香|一局).*多(少|久|长|远)', '使用寿命'),
|
| 134 |
+
(r'多久(换|更换)', '更换周期'),
|
| 135 |
+
(r'(质保|保修).*(多久|多长|几年)', '质保询问'),
|
| 136 |
+
|
| 137 |
+
# ── 问答/是非类(答案是事实不是商品)──
|
| 138 |
+
(r'.{2,}(效果|质量|手感|口感)(好吗|好不好|怎么样)', '产品评价'),
|
| 139 |
+
(r'.{2,}(要|需要).{0,6}吗$', '使用知识'),
|
| 140 |
+
(r'.{2,}能.{0,10}吗$', '使用知识'),
|
| 141 |
+
(r'.{2,}可以.{1,10}吗$', '使用知识'),
|
| 142 |
+
(r'.{2,}是.*(材质|材料|正品|真皮|纯棉|实木|新米|新茶|新款|全新|原装|国产|进口)吗', '属性确认'),
|
| 143 |
+
(r'(显胖|显黑|显白|显高|显矮|显瘦|显老|显嫩|显壮|压身高|压个子|穿.*透)吗', '穿搭是非'),
|
| 144 |
+
(r'(稳固|牢固|结实|耐用|防滑|耐磨|防水|耐高温)吗', '属性确认'),
|
| 145 |
+
(r'(透气|缩水|漏气|掉钻|勾丝|闷热|粘腻|磨脚|漏水|漏电|生锈|褪色|发霉|防滑|耐磨|扎皮肤|扎手).*吗', '属性缺陷'),
|
| 146 |
+
(r'(噪音|误差|味道|气味|色差|辐射|油烟|口感).*(大|小|重|苦|甜|酸|辣|涩|冲|淡).*吗', '属性程度'),
|
| 147 |
+
(r'(包裹性|支撑性|透气性|稳定性|密封性|弹性).*(好|强|够|差).*吗', '属性评价'),
|
| 148 |
+
(r'(透不透|热不热|重不重|硬不硬|闷不闷|粘不粘|厚不厚|软不软|滑不滑)', '属性是非'),
|
| 149 |
+
(r'够.+吗', '属性够否'),
|
| 150 |
+
(r'真的.+吗', '属性确认'),
|
| 151 |
+
(r'适合.*(用|穿|戴|吃|喝).*吗', '适用确认'),
|
| 152 |
+
(r'适合.{2,}(穿|用|戴|吃|喝)$', '适用确认'),
|
| 153 |
+
(r'会不会.+$', '属性确认'),
|
| 154 |
+
(r'(和|跟|与).*(哪个|哪种).*(好用|好|方便|实用)', '产品比较'),
|
| 155 |
+
|
| 156 |
+
# ── 穿搭体型建议 ──
|
| 157 |
+
(r'(小个子|大个子|微胖|矮个|胖|高个子).*(怎么穿|适合穿|穿什么)', '穿搭建议'),
|
| 158 |
+
(r'适合.*(小个子|大个子|微胖|矮个|胖|高个子)', '体型适合'),
|
| 159 |
+
(r'(小个子|微胖|矮个).*(穿|背|戴).*(显|会)', '穿搭是非'),
|
| 160 |
+
|
| 161 |
+
# ── 维修/教程/故障诊断 ──
|
| 162 |
+
(r'怎么(修|修理|维修|修复|配新)', '维修教程'),
|
| 163 |
+
(r'(坏了|不良|故障|损坏).*怎么', '故障维修'),
|
| 164 |
+
(r'(失灵|不灵|不好使).*(是|还是)', '故障诊断'),
|
| 165 |
+
(r'(分辨|辨别|鉴别|辨认|区分).*(正品|真假|真伪)', '鉴别知识'),
|
| 166 |
+
(r'(在哪|哪里).{0,4}(听|看|下载|播放|学)', '使用知识'),
|
| 167 |
+
(r'用在.*(哪一步|第几步|哪步|哪个步骤|哪个环节)', '使用知识'),
|
| 168 |
+
|
| 169 |
+
# ── 产品属性/区别 ──
|
| 170 |
+
(r'(区别|不同).*(在哪|是什么|有什么)', '产品比较'),
|
| 171 |
+
|
| 172 |
+
# ── 适合什么场景/季节 ──
|
| 173 |
+
(r'(适合|针对).*(什么|哪种).*(症状|季节|场景)', '用途场景'),
|
| 174 |
+
(r'什么(季节|时候|场景)(用|穿|戴)', '用途场景'),
|
| 175 |
+
|
| 176 |
+
# ── 同系列/同款/同品牌/款式变体 ──
|
| 177 |
+
(r'同系列.*(还有|其他)', '系列探索'),
|
| 178 |
+
(r'同(款|品牌).*(推荐|还有|有哪些|有没有|生产|出品)', '同款探索'),
|
| 179 |
+
(r'还有.*(同款|其他|什么).*(尺码|规格|款)', '同系列探索'),
|
| 180 |
+
(r'(什么|哪些|哪种|哪个).*(口味|包装|版本)', '款式选择'),
|
| 181 |
+
(r'(长袖|短袖|加长|加大|加厚|薄款|厚款|大号|小号).*(款|版|有哪些|有没有)', '款式变体'),
|
| 182 |
+
(r'(更长|更大|更短|更小|更厚|更薄).*(的|尺寸|尺码|版本|款)', '尺寸变体'),
|
| 183 |
+
|
| 184 |
+
# ── 人群/机型/症状等非商品类型询问 ──
|
| 185 |
+
(r'(哪些|什么).*(人群|机型|车型).*(可以|能|适合|不建议|不适合|不能)', '类型询问'),
|
| 186 |
+
(r'(症状|病症|副作用|禁忌).*(有哪些|是什么|有什么)', '医疗知识'),
|
| 187 |
+
|
| 188 |
+
# ── 食材/早餐搭配 ──
|
| 189 |
+
(r'(加点|加些|配点|配些|放点|放些).*什么', '食材搭配'),
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def classify(query):
|
| 194 |
+
for pattern, rule in EXCLUDE_RULES:
|
| 195 |
+
if re.search(pattern, query):
|
| 196 |
+
return 'exclude', rule
|
| 197 |
+
return 'pending', ''
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def run_rules(args):
|
| 201 |
+
write_jsonl(args.output, [row for row in read_jsonl(args.input)
|
| 202 |
+
if classify(row["query"])[0] != "exclude"])
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# 2. 粗筛:消费已生成的 scene。
|
| 206 |
+
STAGE2_PROMPT = """你在筛选多模态用户 query。根据图像内容、用户意图、原始 query,判断这条 query 属于 keep / discard。
|
| 207 |
+
|
| 208 |
+
【判断步骤】
|
| 209 |
+
1. 用户的需求能否用某个商品解决?
|
| 210 |
+
不能(要的是知识/方法/评价/识别/参数)→ discard
|
| 211 |
+
|
| 212 |
+
2. 这个需求有客观明确的解吗?还是取决于个人审美/喜好?
|
| 213 |
+
取决于个人喜好、没有客观对错的(搭配、配色、风格选择)→ discard
|
| 214 |
+
(如"穿什么好看""用什么颜色适合""配什么风格",答案因人而异)
|
| 215 |
+
|
| 216 |
+
3. 前两关都过 → keep
|
| 217 |
+
|
| 218 |
+
【原则】拿不准就 discard。基于用户真实意图判断,不要脑补需求。
|
| 219 |
+
|
| 220 |
+
【示例】
|
| 221 |
+
图片内容: 生锈的菜刀
|
| 222 |
+
用户意图: 寻找去除菜刀锈迹的工具或用品
|
| 223 |
+
query: 生锈了怎么除锈
|
| 224 |
+
输出: {"reason":"可用"除锈剂"商品解决,有明确解","action":"keep"}
|
| 225 |
+
|
| 226 |
+
图片内容: 牛仔短裙
|
| 227 |
+
用户意图: 了解洗涤牛仔短裙的注意事项
|
| 228 |
+
query: 洗这种面料要注意什么
|
| 229 |
+
输出: {"reason":"要的是洗涤注意事项,属于知识类问答,买商品解决不了该问题","action":"discard"}
|
| 230 |
+
|
| 231 |
+
图片内容: 白衬衫
|
| 232 |
+
用户意图: 寻找搭配白衬衫的裤子
|
| 233 |
+
query: 这件衬衫配什么裤子
|
| 234 |
+
输出: {"reason":"可用"裤子"商品解决,但搭配取决于个人审美,无客观解","action":"discard"}
|
| 235 |
+
|
| 236 |
+
图片内容: 保温水杯
|
| 237 |
+
用户意图: 寻找可以挂在水杯上方便携带的背带绳
|
| 238 |
+
query: 这个水杯出门配个什么绳子好
|
| 239 |
+
输出: {"reason":"可用"水杯背带绳"商品解决,有明确解","action":"keep"}
|
| 240 |
+
|
| 241 |
+
【输入】
|
| 242 |
+
图片内容: __CONTENT__
|
| 243 |
+
用户意图: __INTENT__
|
| 244 |
+
query: __QUERY__
|
| 245 |
+
输出:"""
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def parse_coarse_decision(text):
|
| 249 |
+
obj = extract_json_obj(text)
|
| 250 |
+
action = str(obj.get("action", "")).lower().strip()
|
| 251 |
+
if action not in ("keep", "discard"):
|
| 252 |
+
action = "discard" if "discard" in text.lower() else "keep"
|
| 253 |
+
return {"action": action, "reason": str(obj.get("reason", "")).strip() or text[:80]}
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def run_coarse(model, processor, stage1_path, stage2_path):
|
| 257 |
+
from utils import run_text_only, load_scenes
|
| 258 |
+
scenes = load_scenes(stage1_path)
|
| 259 |
+
done = load_done(stage2_path)
|
| 260 |
+
os.makedirs(os.path.dirname(os.path.abspath(stage2_path)), exist_ok=True)
|
| 261 |
+
n_new = 0
|
| 262 |
+
for idx, row in scenes.items():
|
| 263 |
+
if idx in done:
|
| 264 |
+
continue
|
| 265 |
+
scene = row["scene"]
|
| 266 |
+
prompt = (STAGE2_PROMPT
|
| 267 |
+
.replace("__CONTENT__", scene["content"])
|
| 268 |
+
.replace("__INTENT__", scene["intent"])
|
| 269 |
+
.replace("__QUERY__", row["query"]))
|
| 270 |
+
raw = run_text_only(model, processor, prompt, max_new_tokens=300,
|
| 271 |
+
enable_thinking=False, do_sample=False, seed=0)
|
| 272 |
+
append_jsonl(stage2_path, {**row, "idx": idx, **parse_coarse_decision(raw)})
|
| 273 |
+
n_new += 1
|
| 274 |
+
print(f"初筛完成:新增 {n_new} 条")
|
| 275 |
+
return n_new
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
# 3. 细筛:两个模型独立判断,再取交集。
|
| 279 |
+
DISCARD_AND_CLASSIFY_PROMPT = '''用户发来一张图片并提出问题,想买商品来解决它。你的任务是判断这条 query 是否适合"图+意图→商品检索"这个任务,如果适合,再对它做分类。
|
| 280 |
+
|
| 281 |
+
# 任务背景
|
| 282 |
+
我们要构建的任务是:用户拍一张图 + 说一句只表达意图、不直接点名商品的短文本,模型需要【看图识别对象 + 理解意图 → 推断出能解决问题的商品】。
|
| 283 |
+
好的 query 必须满足:图片提供了关键信息、意图指向一个能用商品解决的明确需求、答案是客观的(有相对确定的商品品类可以对应)。
|
| 284 |
+
|
| 285 |
+
# 输入说明
|
| 286 |
+
你会看到三部分信息:
|
| 287 |
+
- 图片内容、用户提问:这两项合起来是用户最原始的真实需求,判断以此为准。
|
| 288 |
+
- 用户意图:对用户需求的进一步分析,供你参考,帮助你理解用户想要什么。
|
| 289 |
+
注意:用户意图是辅助分析,可能有误或不完整。若它与图片内容/用户提问矛盾,一律以图片内容和用户提问为准。不要因为意图分析把需求"洗白",就放过本该丢弃的 query。
|
| 290 |
+
|
| 291 |
+
# 第一步:判断 keep 还是 discard
|
| 292 |
+
符合下面【任一】丢弃标准,就判为 discard,并给出对应编号。
|
| 293 |
+
|
| 294 |
+
## A 组:答案主观(没有客观正确的商品)
|
| 295 |
+
- A1 搭配/审美类:问搭配什么衣服好看、什么料子/款式好看、怎么穿搭。
|
| 296 |
+
例:"手臂粗适合配什么披肩"、"这种上衣适合配什么裤子"、"日常通勤可以穿什么"、"什么颜色好看"
|
| 297 |
+
- A2 对比/优选类:问怎么挑更好的、哪个效果更好,需要主观权衡。
|
| 298 |
+
例:"怎么挑选保温效果好的"、"敏感肌买哪款好"
|
| 299 |
+
- A3 相似款/配色类:找相似款式、同款、其他配色,本质是图像相似或审美。
|
| 300 |
+
例:"还有哪些相似款式"、"还有哪���其他配色可选"
|
| 301 |
+
|
| 302 |
+
## B 组:缺关键参数,无法确定具体商品
|
| 303 |
+
- B1 精确规格类:答案依赖精确的尺寸/容量/型号,且【图片和文本都无法直接确定】这个规格。
|
| 304 |
+
注意:如果规格能从图/文直接看出(如 Type-C 接口、可见的电池型号),则不算此项,可以保留。
|
| 305 |
+
例(丢弃):"类似容量的推荐哪些"、"适合装在什么样的笔壳里"、"需要多大尺寸的"
|
| 306 |
+
- B2 精确配件类:需要商品的详细参数才能配对的配件。
|
| 307 |
+
例:"原装遥控器丢了怎么重新配"
|
| 308 |
+
- B3 价格约束类:需求里带价格限制(我们的商品库没有价格信息,无法满足)。
|
| 309 |
+
例:"一百块以内有哪些平替"
|
| 310 |
+
|
| 311 |
+
## C 组:不符合任务形式
|
| 312 |
+
- C1 清单/成套类:一次要多种不同商品凑成一套/一个清单(多目标,非单一需求)。
|
| 313 |
+
例:"去海边玩还需要准备什么"、"露营还要准备哪些东西"、"有没有成套的材料包"
|
| 314 |
+
- C2 纯文本可解类:不看图片、只凭文本就能回答,图片没有提供必要信息。
|
| 315 |
+
例:"夹菜工具买哪种不生锈"、"冬天骑电瓶车配哪种挡风被"
|
| 316 |
+
|
| 317 |
+
## D 组:数据质量问题
|
| 318 |
+
- D1 图片模糊/不匹配:图片非常模糊看不清,或图文明显不匹配。
|
| 319 |
+
例:图片糊到认不出物体
|
| 320 |
+
|
| 321 |
+
# 第二步:如果 keep,进行分类
|
| 322 |
+
|
| 323 |
+
## type(功能类型,四选一)
|
| 324 |
+
- T1 配套/使能:识别图中对象/接口 → 推断需要的工具、配件、转接器。
|
| 325 |
+
例:螺丝→螺丝刀;Type-C 接口→转接头
|
| 326 |
+
- T2 恢复/修复/补给:图中物品处于缺失/损坏/耗尽/脏污状态 → 推断替换件、耗材、清洁/维修用品。
|
| 327 |
+
例:电池仓→电池;瓷砖发霉→除霉剂;小白鞋脏了→清洗剂
|
| 328 |
+
- T3 空间/场景约束:图提供空间/尺寸/环境约束 → 检索适配该场景的商品。
|
| 329 |
+
例:厨房窄缝→窄缝收纳架;窄阳台→折叠晾衣架
|
| 330 |
+
- T4 替代/升级:图中是旧的/低效的方案 → 推断某个维度更好的替代品。
|
| 331 |
+
例:白炽灯→LED 灯;普通花洒→增压花洒
|
| 332 |
+
|
| 333 |
+
# 输出格式
|
| 334 |
+
只输出 JSON,不要输出其他内容。
|
| 335 |
+
- 若 discard:{{"decision": "discard", "discard_reason": "编号", "type": null}}
|
| 336 |
+
- 若 keep: {{"decision": "keep", "discard_reason": null, "type": "T1/T2/T3/T4"}}
|
| 337 |
+
|
| 338 |
+
# 示例
|
| 339 |
+
输入:
|
| 340 |
+
图片内容:白色帆布厚底运动鞋(小白鞋),鞋面为白色帆布材质,鞋边有做旧毛边设计,厚底橡胶大底,系带款
|
| 341 |
+
用户提问:脏了用什么洗比较好
|
| 342 |
+
用户意图:寻找清洗白色帆布运动鞋(小白鞋)的洗鞋剂或清洁用品
|
| 343 |
+
输出:
|
| 344 |
+
{{"decision": "keep", "discard_reason": null, "type": "T2"}}
|
| 345 |
+
|
| 346 |
+
输入:
|
| 347 |
+
图片内容:墙上钉着一颗铁钉
|
| 348 |
+
用户提问:怎么把它拔下来
|
| 349 |
+
用户意图:寻找能把墙上的钉子拔出或撬出的工具
|
| 350 |
+
输出:
|
| 351 |
+
{{"decision": "keep", "discard_reason": null, "type": "T1"}}
|
| 352 |
+
|
| 353 |
+
输入:
|
| 354 |
+
图片内容:粉色无袖连衣裙,A字裙摆,圆领,中长款,挂于衣架展示,面料疑似棉质或混纺
|
| 355 |
+
用户提问:手臂粗适合配什么披肩
|
| 356 |
+
用户意图:寻找适合手臂较粗人群搭配该款无袖连衣裙的披肩
|
| 357 |
+
输出:
|
| 358 |
+
{{"decision": "discard", "discard_reason": "A1", "type": null}}
|
| 359 |
+
|
| 360 |
+
输入:
|
| 361 |
+
图片内容:某家用电器(疑似热水器或类似储能/储水类电器)的铭牌标签,标签上印有品牌名称(字迹模糊,疑似"万利达"或类似品牌)、额定电压、额定功率及容量等技术参数,并带有CCC认证标志;因图片模糊,具体容量数值(如升数)无法准确读取
|
| 362 |
+
用户提问:类似容量的推荐哪些
|
| 363 |
+
用户意图:根据图中铭牌所示的容量规格,寻找同类容量的同类电器产品推荐
|
| 364 |
+
输出:
|
| 365 |
+
{{"decision": "discard", "discard_reason": "B1", "type": null}}
|
| 366 |
+
|
| 367 |
+
输入:
|
| 368 |
+
图片内容:泳池场景,前景为一名戴着泳帽和泳镜的婴幼儿,背景中有一名穿粉色连体泳衣、戴紫色遮阳帽的小女孩在池中玩耍,旁边可见浮圈、水上玩具等游泳装备
|
| 369 |
+
用户提问:去海边玩还需要准备什么
|
| 370 |
+
用户意图:图中已有泳帽、泳镜、泳衣等基本装备,用户带小孩去海边玩,想寻找还需补充的海边出行用品(如防晒、安全、娱乐类)
|
| 371 |
+
输出:
|
| 372 |
+
{{"decision": "discard", "discard_reason": "C1", "type": null}}
|
| 373 |
+
|
| 374 |
+
输入:
|
| 375 |
+
图片内容:踏板式电动自行车(电动车),白色/薄荷绿色车身,配有前置车篮,前部挡泥板区域可见明显龟裂纹路(疑似塑料件老化开裂)
|
| 376 |
+
用户提问:冬天骑电瓶车配哪种挡风被
|
| 377 |
+
用户意图:寻找适合该踏板式电动车冬季骑行使用的挡风被(腿部防风罩)
|
| 378 |
+
输出:
|
| 379 |
+
{{"decision": "discard", "discard_reason": "C2", "type": null}}
|
| 380 |
+
|
| 381 |
+
# 本次输入
|
| 382 |
+
图片内容:{content}
|
| 383 |
+
用户提问:{query}
|
| 384 |
+
用户意图:{intent}
|
| 385 |
+
|
| 386 |
+
直接输出 JSON。'''
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
SYSTEM_PROMPT = "你是一个 query 筛选与分类助手。只输出 JSON 对象,不要输出任何解释或���他内容。"
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def load_keep_rows(path):
|
| 393 |
+
with open(path, encoding="utf-8") as f:
|
| 394 |
+
rows = [json.loads(line) for line in f if line.strip()]
|
| 395 |
+
return [dict(row, idx=str(row["idx"])) for row in rows if row["action"] == "keep"]
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def _clean(v):
|
| 399 |
+
"""JSON null -> None;其余去空白。"""
|
| 400 |
+
if v is None:
|
| 401 |
+
return None
|
| 402 |
+
s = str(v).strip()
|
| 403 |
+
return s or None
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def parse_result(text):
|
| 407 |
+
"""从模型输出提取 {decision, discard_reason, type}。"""
|
| 408 |
+
obj = extract_json_obj(text)
|
| 409 |
+
decision = str(obj.get("decision", "")).lower().strip()
|
| 410 |
+
if decision not in ("keep", "discard"):
|
| 411 |
+
raise ValueError("Invalid eligibility response; an explicit keep/discard is required")
|
| 412 |
+
return {
|
| 413 |
+
"decision": decision,
|
| 414 |
+
"discard_reason": _clean(obj.get("discard_reason")),
|
| 415 |
+
"type": _clean(obj.get("type")),
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def call_claude(prompt, model, timeout_seconds):
|
| 420 |
+
result = subprocess.run(
|
| 421 |
+
[
|
| 422 |
+
"claude", "-p", prompt,
|
| 423 |
+
"--system-prompt", SYSTEM_PROMPT,
|
| 424 |
+
"--model", model,
|
| 425 |
+
"--output-format", "text",
|
| 426 |
+
"--no-session-persistence",
|
| 427 |
+
"--bare",
|
| 428 |
+
],
|
| 429 |
+
stdin=subprocess.DEVNULL,
|
| 430 |
+
capture_output=True,
|
| 431 |
+
text=True,
|
| 432 |
+
timeout=timeout_seconds,
|
| 433 |
+
)
|
| 434 |
+
if result.returncode != 0:
|
| 435 |
+
stderr = (result.stderr or "").strip()
|
| 436 |
+
raise RuntimeError(f"claude -p exit {result.returncode}: {stderr}")
|
| 437 |
+
return result.stdout.strip()
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def call_claude_with_retry(prompt, model, max_retries, timeout_seconds):
|
| 441 |
+
for attempt in range(1, max_retries + 1):
|
| 442 |
+
try:
|
| 443 |
+
raw = call_claude(prompt, model, timeout_seconds)
|
| 444 |
+
parse_result(raw)
|
| 445 |
+
return raw, None
|
| 446 |
+
except Exception as exc:
|
| 447 |
+
if attempt == max_retries:
|
| 448 |
+
return None, str(exc)
|
| 449 |
+
time.sleep(min(2 ** attempt, 10))
|
| 450 |
+
return None, "max retries exceeded"
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def build_prompt(row):
|
| 454 |
+
return DISCARD_AND_CLASSIFY_PROMPT.format(
|
| 455 |
+
content=row["scene"]["content"], query=row["query"], intent=row["scene"]["intent"])
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def run_fine(args):
|
| 459 |
+
rows = load_keep_rows(args.input)
|
| 460 |
+
done = load_done(args.output)
|
| 461 |
+
os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
|
| 462 |
+
|
| 463 |
+
def process_one(row):
|
| 464 |
+
raw, error = call_claude_with_retry(
|
| 465 |
+
build_prompt(row), args.model, args.max_retries, args.timeout)
|
| 466 |
+
if error:
|
| 467 |
+
raise RuntimeError(f"idx={row['idx']}: {error}")
|
| 468 |
+
append_jsonl(args.output, {**row, **parse_result(raw), "raw_response": raw})
|
| 469 |
+
|
| 470 |
+
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
| 471 |
+
futures = [pool.submit(process_one, row) for row in rows if row["idx"] not in done]
|
| 472 |
+
for future in as_completed(futures):
|
| 473 |
+
future.result()
|
| 474 |
+
print(f"资格判定完成:{args.output}")
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def load_votes(path):
|
| 478 |
+
records = {}
|
| 479 |
+
with open(path, encoding="utf-8") as f:
|
| 480 |
+
for line in f:
|
| 481 |
+
line = line.strip()
|
| 482 |
+
if not line:
|
| 483 |
+
continue
|
| 484 |
+
r = json.loads(line)
|
| 485 |
+
records[str(r["idx"])] = r
|
| 486 |
+
return records
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def merge_eligibility(glm_path, ds_path, out_path):
|
| 490 |
+
glm, ds = load_votes(glm_path), load_votes(ds_path)
|
| 491 |
+
if set(glm) != set(ds):
|
| 492 |
+
raise ValueError("Eligibility models must cover the same query IDs")
|
| 493 |
+
kept = []
|
| 494 |
+
for idx, row in glm.items():
|
| 495 |
+
other = ds.get(idx)
|
| 496 |
+
if row["decision"] == "keep" and other and other["decision"] == "keep":
|
| 497 |
+
kept.append({"idx": idx, "query": row["query"], "image_url": row["image_url"],
|
| 498 |
+
"scene": row["scene"], "type": other["type"]})
|
| 499 |
+
with open(out_path, "w", encoding="utf-8") as f:
|
| 500 |
+
for row in kept:
|
| 501 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 502 |
+
print(f"双模型均通过:{len(kept)} 条,保存到 {out_path}")
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
# 4. 意图向量去重。
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def run_dedup(args):
|
| 509 |
+
items = read_jsonl(args.input)
|
| 510 |
+
if args.emb_path:
|
| 511 |
+
emb = load_embeddings(args.emb_path, [row["idx"] for row in items])
|
| 512 |
+
else:
|
| 513 |
+
from sentence_transformers import SentenceTransformer
|
| 514 |
+
model = SentenceTransformer(args.model, model_kwargs={"torch_dtype": "bfloat16"})
|
| 515 |
+
model.max_seq_length = 512
|
| 516 |
+
emb = model.encode([row["scene"]["intent"] for row in items], batch_size=64,
|
| 517 |
+
convert_to_numpy=True, normalize_embeddings=True, show_progress_bar=True)
|
| 518 |
+
kept, mapping = deduplicate(items, emb, "query", args.threshold)
|
| 519 |
+
out = Path(args.output_dir)
|
| 520 |
+
write_jsonl(out / "deduplicated.jsonl", kept)
|
| 521 |
+
(out / "id_mapping.json").write_text(json.dumps(mapping, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 522 |
+
print(f"Query 去重:{len(items)} → {len(kept)}")
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def main():
|
| 526 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 527 |
+
sub = p.add_subparsers(dest="stage", required=True)
|
| 528 |
+
for stage in ("rules", "coarse", "fine", "merge", "dedup"):
|
| 529 |
+
command = sub.add_parser(stage)
|
| 530 |
+
if stage == "merge":
|
| 531 |
+
command.add_argument("--glm", required=True)
|
| 532 |
+
command.add_argument("--ds", required=True)
|
| 533 |
+
else:
|
| 534 |
+
command.add_argument("--input", required=True)
|
| 535 |
+
command.add_argument("--output-dir" if stage == "dedup" else "--output", required=True)
|
| 536 |
+
if stage == "coarse":
|
| 537 |
+
command.add_argument("--model-path", required=True)
|
| 538 |
+
elif stage == "fine":
|
| 539 |
+
command.add_argument("--model", required=True, choices=["GLM-5.2", "deepseek-v4-pro"])
|
| 540 |
+
command.add_argument("--concurrency", type=int, default=8)
|
| 541 |
+
command.add_argument("--max-retries", type=int, default=3)
|
| 542 |
+
command.add_argument("--timeout", type=int, default=120)
|
| 543 |
+
elif stage == "dedup":
|
| 544 |
+
command.add_argument("--emb-path", help="NPZ with emb and ids in input order")
|
| 545 |
+
command.add_argument("--model", default="Qwen/Qwen3-Embedding-8B")
|
| 546 |
+
command.add_argument("--threshold", type=float, default=0.70)
|
| 547 |
+
args = p.parse_args()
|
| 548 |
+
if args.stage == "rules":
|
| 549 |
+
run_rules(args)
|
| 550 |
+
elif args.stage == "coarse":
|
| 551 |
+
model, processor = load_model_and_processor(args.model_path)
|
| 552 |
+
run_coarse(model, processor, args.input, args.output)
|
| 553 |
+
elif args.stage == "fine":
|
| 554 |
+
run_fine(args)
|
| 555 |
+
elif args.stage == "merge":
|
| 556 |
+
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
| 557 |
+
merge_eligibility(args.glm, args.ds, args.output)
|
| 558 |
+
else:
|
| 559 |
+
run_dedup(args)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
if __name__ == "__main__":
|
| 563 |
+
main()
|
construction/retrieve_candidates.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""商品词走三路检索,意图走文本融合和多模态两路;每源默认 top-5。
|
| 2 |
+
|
| 3 |
+
search(mode, queries, top_k) 由调用方提供,不在本文件实现检索后端。
|
| 4 |
+
queries 为 {query_id: text},返回 {query_id: [(item_id, score), ...]},按分数降序。
|
| 5 |
+
mode: bm25(jieba 分词);embedding(Qwen3-Embedding-0.6B 与
|
| 6 |
+
BGE-small-zh-v1.5 的 RRF 融合);qwen3_vl(Qwen3-VL-Embedding-2B)。
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from utils import deduplicate, load_embeddings, read_jsonl, write_jsonl
|
| 13 |
+
|
| 14 |
+
MODES = ("bm25", "embedding", "qwen3_vl")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def retrieve_candidates(input_path, output_path, search, top_k=5):
|
| 18 |
+
with open(input_path, encoding="utf-8") as f:
|
| 19 |
+
entries = [json.loads(line) for line in f if line.strip()]
|
| 20 |
+
keywords = dict.fromkeys(kw for row in entries for kw in row["product_keywords"])
|
| 21 |
+
intents = dict.fromkeys(row["scene"]["intent"] for row in entries if row["scene"]["intent"])
|
| 22 |
+
kw_to_qid = {kw: f"kw_{i}" for i, kw in enumerate(keywords)}
|
| 23 |
+
intent_to_qid = {intent: f"int_{i}" for i, intent in enumerate(intents)}
|
| 24 |
+
kw_queries = {qid: kw for kw, qid in kw_to_qid.items()}
|
| 25 |
+
intent_queries = {qid: intent for intent, qid in intent_to_qid.items()}
|
| 26 |
+
mode_results = {}
|
| 27 |
+
for mode in MODES:
|
| 28 |
+
queries = kw_queries if mode == "bm25" else {**kw_queries, **intent_queries}
|
| 29 |
+
mode_results[mode] = search(mode, queries, top_k=top_k)
|
| 30 |
+
output = [assemble_sources(row, mode_results, kw_to_qid, intent_to_qid, top_k)
|
| 31 |
+
for row in entries]
|
| 32 |
+
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
with open(output_path, "w", encoding="utf-8") as f:
|
| 34 |
+
for row in output:
|
| 35 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 36 |
+
return output
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def assemble_sources(row, mode_results, kw_to_qid, intent_to_qid, top_k=5):
|
| 40 |
+
searches = [(kw, kw_to_qid[kw], "keyword") for kw in row["product_keywords"]]
|
| 41 |
+
intent = row["scene"]["intent"]
|
| 42 |
+
if intent:
|
| 43 |
+
searches.append((intent, intent_to_qid[intent], "intent"))
|
| 44 |
+
sources = []
|
| 45 |
+
for text, qid, kind in searches:
|
| 46 |
+
for mode in MODES:
|
| 47 |
+
if kind == "intent" and mode == "bm25":
|
| 48 |
+
continue
|
| 49 |
+
hits = mode_results[mode].get(qid, [])[:top_k]
|
| 50 |
+
sources.append({
|
| 51 |
+
"source": f"{mode}:{text if kind == 'keyword' else 'intent'}",
|
| 52 |
+
"mode": mode, "query_text": text, "query_type": kind,
|
| 53 |
+
"items": [{"item_id": did, "score": score, "rank": rank}
|
| 54 |
+
for rank, (did, score) in enumerate(hits, 1)],
|
| 55 |
+
})
|
| 56 |
+
return {"idx": row["idx"], "query": row["query"], "image_url": row["image_url"],
|
| 57 |
+
"scene": row["scene"], "product_keywords": row["product_keywords"],
|
| 58 |
+
"source_results": sources}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# 叶类目内去重,随后合并并重定向各 query 的候选。
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def redirect_candidates(entries, product_mapping):
|
| 65 |
+
"""将检索源结果合并为 query-product 对,重定向商品并合并来源。"""
|
| 66 |
+
pairs = {}
|
| 67 |
+
for row in entries:
|
| 68 |
+
for source in row["source_results"]:
|
| 69 |
+
for hit in source["items"]:
|
| 70 |
+
item_id = product_mapping[str(hit["item_id"])]
|
| 71 |
+
key = (str(row["idx"]), item_id)
|
| 72 |
+
pair = pairs.setdefault(key, {"idx": key[0], "item_id": item_id, "retrieved_by": []})
|
| 73 |
+
if source["source"] not in pair["retrieved_by"]:
|
| 74 |
+
pair["retrieved_by"].append(source["source"])
|
| 75 |
+
return list(pairs.values())
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def run_product_dedup(args):
|
| 79 |
+
items = read_jsonl(args.input)
|
| 80 |
+
emb = load_embeddings(args.emb_path, [row["item_id"] for row in items])
|
| 81 |
+
kept, mapping = deduplicate(items, emb, "product", args.threshold)
|
| 82 |
+
pairs = redirect_candidates(read_jsonl(args.sources), mapping)
|
| 83 |
+
out = Path(args.output_dir)
|
| 84 |
+
write_jsonl(out / "deduplicated.jsonl", kept)
|
| 85 |
+
write_jsonl(out / "pairs.jsonl", pairs)
|
| 86 |
+
(out / "id_mapping.json").write_text(json.dumps(mapping, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 87 |
+
print(f"商品去重:{len(items)} → {len(kept)}")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def main():
|
| 91 |
+
p = argparse.ArgumentParser(description="候选商品去重及 query-product 对重定向")
|
| 92 |
+
p.add_argument("--input", required=True, help="召回商品并集 JSONL")
|
| 93 |
+
p.add_argument("--emb-path", required=True, help="Qwen3-VL-Embedding-8B 图文 NPZ: emb, ids")
|
| 94 |
+
p.add_argument("--sources", required=True, help="retrieve_candidates 输出的 source_results")
|
| 95 |
+
p.add_argument("--output-dir", required=True)
|
| 96 |
+
p.add_argument("--threshold", type=float, default=0.60)
|
| 97 |
+
run_product_dedup(p.parse_args())
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
main()
|
construction/utils.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared parsing, JSONL and local-model helpers extracted from the original code."""
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
PROJECT_ROOT = Path(__file__).resolve().parent
|
| 9 |
+
RESULTS_DIR = PROJECT_ROOT / "work" / "candidate_discovery"
|
| 10 |
+
STAGE1_OUT = str(PROJECT_ROOT / "work" / "query_curation" / "intent.jsonl")
|
| 11 |
+
MODEL_PATH = str(PROJECT_ROOT / "models" / "Qwen" / "Qwen3.6-27B")
|
| 12 |
+
MAX_IMAGE_PIXELS = 2 * 1024 * 1024
|
| 13 |
+
|
| 14 |
+
def extract_json_obj(text):
|
| 15 |
+
"""Extract a JSON object ({...}) from model output. Returns dict or fallback."""
|
| 16 |
+
try:
|
| 17 |
+
match = re.search(r"\{.*\}", text, re.DOTALL)
|
| 18 |
+
if match:
|
| 19 |
+
parsed = json.loads(match.group())
|
| 20 |
+
if isinstance(parsed, dict):
|
| 21 |
+
return parsed
|
| 22 |
+
except (json.JSONDecodeError, ValueError):
|
| 23 |
+
pass
|
| 24 |
+
return {"content": "未知", "intent": "未知", "note": "未知", "_raw": text}
|
| 25 |
+
|
| 26 |
+
def extract_keywords(text):
|
| 27 |
+
try:
|
| 28 |
+
match = re.search(r"\[.*?\]", text, re.DOTALL)
|
| 29 |
+
if match:
|
| 30 |
+
parsed = json.loads(match.group())
|
| 31 |
+
if isinstance(parsed, list) and all(isinstance(x, str) for x in parsed):
|
| 32 |
+
return parsed
|
| 33 |
+
except (json.JSONDecodeError, ValueError):
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
lines = text.strip().split("\n")
|
| 37 |
+
keywords = []
|
| 38 |
+
for line in lines:
|
| 39 |
+
line = line.strip()
|
| 40 |
+
cleaned = re.sub(r"^[\d]+[.、)\]]\s*", "", line)
|
| 41 |
+
cleaned = re.sub(r"^[-*·•]\s*", "", cleaned)
|
| 42 |
+
cleaned = re.sub(r"\*\*(.+?)\*\*", r"\1", cleaned)
|
| 43 |
+
cleaned = cleaned.split(":")[0].split(":")[0].strip()
|
| 44 |
+
if cleaned and len(cleaned) < 30:
|
| 45 |
+
keywords.append(cleaned)
|
| 46 |
+
|
| 47 |
+
if not keywords:
|
| 48 |
+
keywords = [k.strip() for k in text.split(",") if k.strip()]
|
| 49 |
+
if not keywords:
|
| 50 |
+
keywords = [k.strip() for k in text.split(",") if k.strip()]
|
| 51 |
+
|
| 52 |
+
return keywords[:15]
|
| 53 |
+
|
| 54 |
+
def append_result(result, pipeline_name, out_dir=None):
|
| 55 |
+
"""增量追加 JSONL。"""
|
| 56 |
+
base = Path(out_dir) if out_dir is not None else RESULTS_DIR
|
| 57 |
+
base.mkdir(exist_ok=True, parents=True)
|
| 58 |
+
out_path = base / f"{pipeline_name}.jsonl"
|
| 59 |
+
with open(out_path, "a", encoding="utf-8") as f:
|
| 60 |
+
f.write(json.dumps(result, ensure_ascii=False) + "\n")
|
| 61 |
+
f.flush()
|
| 62 |
+
|
| 63 |
+
def load_done_idx(pipeline_name, out_dir=None):
|
| 64 |
+
"""读取已完成的 idx 集合,用于断点续存跳过。"""
|
| 65 |
+
base = Path(out_dir) if out_dir is not None else RESULTS_DIR
|
| 66 |
+
base.mkdir(exist_ok=True, parents=True)
|
| 67 |
+
out_path = base / f"{pipeline_name}.jsonl"
|
| 68 |
+
done = set()
|
| 69 |
+
if out_path.exists():
|
| 70 |
+
with open(out_path, encoding="utf-8") as f:
|
| 71 |
+
for line in f:
|
| 72 |
+
line = line.strip()
|
| 73 |
+
if line:
|
| 74 |
+
try:
|
| 75 |
+
done.add(json.loads(line)["idx"])
|
| 76 |
+
except (json.JSONDecodeError, KeyError):
|
| 77 |
+
continue
|
| 78 |
+
return done
|
| 79 |
+
|
| 80 |
+
def load_scenes(stage1_path=None):
|
| 81 |
+
"""读 Stage1 缓存 -> {idx: scene_dict}。这是下游模块消费 Stage1 输出的主接口。"""
|
| 82 |
+
path = stage1_path or STAGE1_OUT
|
| 83 |
+
scenes = {}
|
| 84 |
+
if os.path.exists(path):
|
| 85 |
+
with open(path, encoding="utf-8") as f:
|
| 86 |
+
for line in f:
|
| 87 |
+
line = line.strip()
|
| 88 |
+
if not line:
|
| 89 |
+
continue
|
| 90 |
+
try:
|
| 91 |
+
r = json.loads(line)
|
| 92 |
+
scenes[str(r["idx"])] = r
|
| 93 |
+
except (json.JSONDecodeError, KeyError):
|
| 94 |
+
continue
|
| 95 |
+
return scenes
|
| 96 |
+
|
| 97 |
+
def load_model_and_processor(model_path=None):
|
| 98 |
+
import torch
|
| 99 |
+
from transformers import AutoProcessor, Qwen3_5ForConditionalGeneration
|
| 100 |
+
path = model_path or MODEL_PATH
|
| 101 |
+
print(f"Loading processor from {path} ...")
|
| 102 |
+
processor = AutoProcessor.from_pretrained(path, trust_remote_code=True)
|
| 103 |
+
# 限制图片分辨率。
|
| 104 |
+
processor.image_processor.size["longest_edge"] = MAX_IMAGE_PIXELS
|
| 105 |
+
print(f" max_pixels(longest_edge)={MAX_IMAGE_PIXELS}")
|
| 106 |
+
|
| 107 |
+
print(f"Loading model (bf16, device_map=cuda) from {path} ...")
|
| 108 |
+
t0 = time.time()
|
| 109 |
+
model = Qwen3_5ForConditionalGeneration.from_pretrained(
|
| 110 |
+
path,
|
| 111 |
+
dtype=torch.bfloat16,
|
| 112 |
+
device_map="cuda",
|
| 113 |
+
trust_remote_code=True,
|
| 114 |
+
)
|
| 115 |
+
model.eval()
|
| 116 |
+
print(f"Model loaded in {time.time() - t0:.1f}s")
|
| 117 |
+
return model, processor
|
| 118 |
+
|
| 119 |
+
def strip_think_block(text):
|
| 120 |
+
return re.sub(r"🤔.*?</think>\s*", "", text, flags=re.DOTALL).strip()
|
| 121 |
+
|
| 122 |
+
def run_text_only(model, processor, text_prompt, max_new_tokens=1024, enable_thinking=False,
|
| 123 |
+
do_sample=True, temperature=0.7, top_p=0.8, top_k=20, seed=None):
|
| 124 |
+
import torch
|
| 125 |
+
"""纯文本推理(单条)。采样参数语义同 run_multimodal:默认采样兼容旧 pipeline,
|
| 126 |
+
需可复现时传 do_sample=False + seed=0。"""
|
| 127 |
+
tokenizer = processor.tokenizer
|
| 128 |
+
messages = [{"role": "user", "content": text_prompt}]
|
| 129 |
+
text = tokenizer.apply_chat_template(
|
| 130 |
+
messages, tokenize=False, add_generation_prompt=True,
|
| 131 |
+
enable_thinking=enable_thinking,
|
| 132 |
+
)
|
| 133 |
+
inputs = tokenizer(text, return_tensors="pt").to(model.device)
|
| 134 |
+
if seed is not None:
|
| 135 |
+
torch.manual_seed(seed)
|
| 136 |
+
if torch.cuda.is_available():
|
| 137 |
+
torch.cuda.manual_seed_all(seed)
|
| 138 |
+
gen_kwargs = dict(max_new_tokens=max_new_tokens, do_sample=do_sample)
|
| 139 |
+
if do_sample:
|
| 140 |
+
gen_kwargs.update(temperature=temperature, top_p=top_p, top_k=top_k)
|
| 141 |
+
with torch.no_grad():
|
| 142 |
+
output_ids = model.generate(**inputs, **gen_kwargs)
|
| 143 |
+
generated = output_ids[0][inputs["input_ids"].shape[1]:]
|
| 144 |
+
response = tokenizer.decode(generated, skip_special_tokens=True)
|
| 145 |
+
if enable_thinking:
|
| 146 |
+
return strip_think_block(response)
|
| 147 |
+
return response.strip()
|
| 148 |
+
|
| 149 |
+
def run_text_only_batch(model, processor, prompts, batch_size=8, max_new_tokens=256,
|
| 150 |
+
enable_thinking=False, do_sample=True, temperature=0.7,
|
| 151 |
+
top_p=0.8, top_k=20, seed=None, sort_by_length=False,
|
| 152 |
+
show_progress=True):
|
| 153 |
+
import torch
|
| 154 |
+
"""批量纯文本推理,保留输入顺序。"""
|
| 155 |
+
tokenizer = processor.tokenizer
|
| 156 |
+
n = len(prompts)
|
| 157 |
+
if n == 0:
|
| 158 |
+
return []
|
| 159 |
+
|
| 160 |
+
# 1. 套 chat template(不 tokenize,留待批量 padding)
|
| 161 |
+
chat_texts = []
|
| 162 |
+
for p in prompts:
|
| 163 |
+
messages = [{"role": "user", "content": p}]
|
| 164 |
+
chat_texts.append(tokenizer.apply_chat_template(
|
| 165 |
+
messages, tokenize=False, add_generation_prompt=True,
|
| 166 |
+
enable_thinking=enable_thinking,
|
| 167 |
+
))
|
| 168 |
+
|
| 169 |
+
# 2. 分桶顺序(按 prompt 长度升序,连续分批 → 同批长度接近、padding 最少)
|
| 170 |
+
order = list(range(n))
|
| 171 |
+
if sort_by_length:
|
| 172 |
+
lens = [len(tokenizer(t, add_special_tokens=False)["input_ids"]) for t in chat_texts]
|
| 173 |
+
order.sort(key=lambda i: lens[i])
|
| 174 |
+
|
| 175 |
+
# 3. 设置 left-padding(decoder-only 生成必须)+ pad token
|
| 176 |
+
prev_side = tokenizer.padding_side
|
| 177 |
+
if tokenizer.pad_token is None:
|
| 178 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 179 |
+
tokenizer.padding_side = "left"
|
| 180 |
+
|
| 181 |
+
results = [None] * n
|
| 182 |
+
n_batches = (n + batch_size - 1) // batch_size
|
| 183 |
+
try:
|
| 184 |
+
gen_kwargs = dict(max_new_tokens=max_new_tokens, do_sample=do_sample)
|
| 185 |
+
if do_sample:
|
| 186 |
+
gen_kwargs.update(temperature=temperature, top_p=top_p, top_k=top_k)
|
| 187 |
+
for bi, b_start in enumerate(range(0, n, batch_size)):
|
| 188 |
+
batch_idx = order[b_start:b_start + batch_size]
|
| 189 |
+
batch_texts = [chat_texts[i] for i in batch_idx]
|
| 190 |
+
inputs = tokenizer(
|
| 191 |
+
batch_texts, padding=True, return_tensors="pt",
|
| 192 |
+
).to(model.device)
|
| 193 |
+
if seed is not None:
|
| 194 |
+
torch.manual_seed(seed)
|
| 195 |
+
if torch.cuda.is_available():
|
| 196 |
+
torch.cuda.manual_seed_all(seed)
|
| 197 |
+
with torch.no_grad():
|
| 198 |
+
output_ids = model.generate(**inputs, **gen_kwargs)
|
| 199 |
+
# left-pad 下所有行 prompt 都被右对齐到同一长度,切掉前 input_len 即得新生成
|
| 200 |
+
input_len = inputs["input_ids"].shape[1]
|
| 201 |
+
gen_ids = output_ids[:, input_len:]
|
| 202 |
+
for j, i in enumerate(batch_idx):
|
| 203 |
+
text = tokenizer.decode(gen_ids[j], skip_special_tokens=True)
|
| 204 |
+
if enable_thinking:
|
| 205 |
+
text = strip_think_block(text)
|
| 206 |
+
results[i] = text.strip()
|
| 207 |
+
if show_progress:
|
| 208 |
+
done = b_start + len(batch_idx)
|
| 209 |
+
print(f" batch {bi + 1}/{n_batches} done ({done}/{n})", flush=True)
|
| 210 |
+
finally:
|
| 211 |
+
tokenizer.padding_side = prev_side
|
| 212 |
+
|
| 213 |
+
return results
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
GRADE_ALIASES = {"L1": "L1", "L2": "L2", "N1": "N1", "N2": "N2", "N3": "N3",
|
| 218 |
+
"hard_neg_constraint": "N1", "hard_neg_lookalike": "N2", "irrelevant": "N3"}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def parse_grade(text):
|
| 222 |
+
"""Require an explicit valid JSON label; failed generation is not a vote."""
|
| 223 |
+
obj = extract_json_obj(text)
|
| 224 |
+
grade = obj.get("grade")
|
| 225 |
+
if not isinstance(grade, str) or grade not in GRADE_ALIASES:
|
| 226 |
+
raise ValueError("Model response does not contain a valid five-way grade")
|
| 227 |
+
internal = {"N1": "hard_neg_constraint", "N2": "hard_neg_lookalike", "N3": "irrelevant"}
|
| 228 |
+
return {"grade": internal.get(grade, grade), "reason": obj.get("reason")}
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def read_jsonl(path):
|
| 232 |
+
with open(path, encoding="utf-8") as f:
|
| 233 |
+
return [json.loads(line) for line in f if line.strip()]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def write_jsonl(path, rows):
|
| 237 |
+
path = Path(path)
|
| 238 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 239 |
+
with path.open("w", encoding="utf-8") as f:
|
| 240 |
+
for row in rows:
|
| 241 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def read_pairs(path):
|
| 245 |
+
"""Accept flat pairs or the historical per-query candidates format."""
|
| 246 |
+
pairs = []
|
| 247 |
+
for row in read_jsonl(path):
|
| 248 |
+
if "item_id" in row:
|
| 249 |
+
candidates = [row]
|
| 250 |
+
elif isinstance(row.get("candidates"), list):
|
| 251 |
+
candidates = row["candidates"]
|
| 252 |
+
else:
|
| 253 |
+
raise ValueError(f"Expected item_id or candidates in {path}")
|
| 254 |
+
for candidate in candidates:
|
| 255 |
+
pairs.append({**candidate, "idx": str(row["idx"]),
|
| 256 |
+
"item_id": str(candidate["item_id"])})
|
| 257 |
+
return pairs
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def pair_key(row):
|
| 261 |
+
return str(row["idx"]), str(row["item_id"])
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def index_pairs(rows):
|
| 265 |
+
indexed = {}
|
| 266 |
+
for row in rows:
|
| 267 |
+
key = pair_key(row)
|
| 268 |
+
if key in indexed:
|
| 269 |
+
raise ValueError(f"Duplicate pair: {key}")
|
| 270 |
+
indexed[key] = row
|
| 271 |
+
return indexed
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def leader_clusters(sub, gidxs, threshold):
|
| 275 |
+
"""按中心性降序分配;只吸收与 leader 直接相似的成员。sub 对角为 -1。"""
|
| 276 |
+
m = len(gidxs)
|
| 277 |
+
if m <= 1:
|
| 278 |
+
return [list(gidxs)] if m else []
|
| 279 |
+
cent = (sub.sum(axis=1) + 1.0) / (m - 1)
|
| 280 |
+
order = sorted(range(m), key=lambda i: -float(cent[i]))
|
| 281 |
+
assigned = [False] * m
|
| 282 |
+
clusters = []
|
| 283 |
+
for li in order:
|
| 284 |
+
if assigned[li]:
|
| 285 |
+
continue
|
| 286 |
+
members = [li]
|
| 287 |
+
assigned[li] = True
|
| 288 |
+
for j in order:
|
| 289 |
+
if assigned[j] or j == li:
|
| 290 |
+
continue
|
| 291 |
+
if float(sub[li][j]) >= threshold:
|
| 292 |
+
members.append(j)
|
| 293 |
+
assigned[j] = True
|
| 294 |
+
clusters.append([gidxs[x] for x in members])
|
| 295 |
+
return clusters
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def select_representative(members, emb, kind):
|
| 299 |
+
import numpy as np
|
| 300 |
+
sub = emb[members]
|
| 301 |
+
if kind == "query":
|
| 302 |
+
centroid = sub.mean(axis=0)
|
| 303 |
+
centroid /= np.linalg.norm(centroid) + 1e-9
|
| 304 |
+
scores = sub @ centroid
|
| 305 |
+
else:
|
| 306 |
+
sim = sub @ sub.T
|
| 307 |
+
np.fill_diagonal(sim, 0)
|
| 308 |
+
scores = sim.sum(axis=1) / max(len(members) - 1, 1)
|
| 309 |
+
return members[int(np.argmax(scores))]
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def deduplicate(items, emb, kind, threshold=None):
|
| 313 |
+
import numpy as np
|
| 314 |
+
from collections import defaultdict
|
| 315 |
+
threshold = threshold if threshold is not None else (0.70 if kind == "query" else 0.60)
|
| 316 |
+
emb = np.asarray(emb, dtype=np.float32)
|
| 317 |
+
if emb.ndim != 2 or len(emb) != len(items):
|
| 318 |
+
raise ValueError("向量行数必须与输入记录一一对应")
|
| 319 |
+
norms = np.linalg.norm(emb, axis=1, keepdims=True)
|
| 320 |
+
if not np.isfinite(emb).all() or (norms == 0).any():
|
| 321 |
+
raise ValueError("向量必须有限且非零")
|
| 322 |
+
emb = emb / norms
|
| 323 |
+
buckets = defaultdict(list)
|
| 324 |
+
for i, row in enumerate(items):
|
| 325 |
+
key = row["treecate_full_path"] if kind == "product" else "all"
|
| 326 |
+
if not key:
|
| 327 |
+
raise ValueError("商品必须有叶子类目的完整路径")
|
| 328 |
+
buckets[key].append(i)
|
| 329 |
+
kept, mapping = [], {}
|
| 330 |
+
id_key = "idx" if kind == "query" else "item_id"
|
| 331 |
+
for indices in buckets.values():
|
| 332 |
+
sim = emb[indices] @ emb[indices].T
|
| 333 |
+
np.fill_diagonal(sim, -1)
|
| 334 |
+
for members in leader_clusters(sim, indices, threshold):
|
| 335 |
+
rep = select_representative(members, emb, kind)
|
| 336 |
+
kept.append(rep)
|
| 337 |
+
for i in members:
|
| 338 |
+
mapping[str(items[i][id_key])] = str(items[rep][id_key])
|
| 339 |
+
return [items[i] for i in sorted(kept)], mapping
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def load_embeddings(path, ids):
|
| 343 |
+
import numpy as np
|
| 344 |
+
with np.load(path, allow_pickle=False) as data:
|
| 345 |
+
if list(map(str, data["ids"])) != list(map(str, ids)):
|
| 346 |
+
raise ValueError("向量缓存的 ID 顺序与输入不一致")
|
| 347 |
+
return data["emb"]
|
data/README.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIPR data
|
| 2 |
+
|
| 3 |
+
| File / directory | Contents |
|
| 4 |
+
|---|---|
|
| 5 |
+
| `mipr_query.jsonl` | Queries: `idx`, original `query`, and local image filename `image_url` |
|
| 6 |
+
| `mipr_corpus.jsonl` | Products: `item_id`, `title`, local image filename `pict_url`, and leaf category path `treecate_full_path` |
|
| 7 |
+
| `mipr_annotation.jsonl` | Pooled five-grade relevance judgments, grouped by query |
|
| 8 |
+
| `images/query_images/` | Query images referenced by `image_url` |
|
| 9 |
+
| `images/product_images/` | Product images referenced by `pict_url` |
|
| 10 |
+
| `baseline/` | Saved top-50 rankings for retrieval and reranking evaluation |
|
| 11 |
+
|
| 12 |
+
## Baseline rankings
|
| 13 |
+
|
| 14 |
+
`baseline/qwen3_vl_embedding_8b_top50.json` contains the top-50 retrieval results from Qwen3-VL-Embedding-8B. `baseline/qwen3_vl_reranker_8b_top50.json` contains the same candidate pool reordered by Qwen3-VL-Reranker-8B.
|
| 15 |
+
|
| 16 |
+
These are JSON rankings, not model weights or embedding arrays. Each file contains 3,522 query entries with `qid` and `ranked`; each ranked item has `did` and `score`. They allow evaluation of the saved results without running model inference.
|
| 17 |
+
|
| 18 |
+
From the release root:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
python evaluation/evaluate.py data/baseline/qwen3_vl_embedding_8b_top50.json
|
| 22 |
+
python evaluation/evaluate.py data/baseline/qwen3_vl_reranker_8b_top50.json --rerank
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
See the [main README](../README.md) for data schemas, relevance grades and metrics.
|
data/baseline/qwen3_vl_embedding_8b_top50.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/baseline/qwen3_vl_reranker_8b_top50.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/images/product_images/000141ffc3d968e5.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0006623597fe4213.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/000775e4cb9e5bee.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00081bd03b1e69bc.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00086a198e7e3720.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0010f82ecfcecd62.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00111db572ce2424.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0011beb14ff9c526.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00158ff2ea36023b.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0017ed7e7c7bc2a3.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0018037a3d23186d.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/001d2bccf8ac8ae1.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00232ef0569c5e45.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/002acec3b6a8e31a.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/002e059a9eacc8d3.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/002e837a45283524.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/002ff89c71d2926d.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00349e1c137b59a7.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0035b57acec1f213.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00366bfa06ee7744.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/003850fa8ca517d1.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/003dfb4e0c85d7e7.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00409c85919a3b23.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0042d6c8a8f54f8e.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/004367b9f70249fd.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0045d2477c93508b.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0046ff19c63a1516.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/0047608eca71adc7.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/004b916e301ba550.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/004cee587cb7e532.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/004fd209343d8145.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/004fea38f2d55e28.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/005310cc94a625ed.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00534ab388a2fae5.jpg
ADDED
|
Git LFS Details
|
data/images/product_images/00541941dd61a731.jpg
ADDED
|
Git LFS Details
|