Spaces:
Sleeping
Sleeping
Ashwath Vaithinathan Aravindan
commited on
Commit
·
773f1d0
0
Parent(s):
test-spaces
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .DS_Store +0 -0
- .gitattributes +2 -0
- CHANGELOG.md +13 -0
- CODE_OF_CONDUCT.md +76 -0
- CONTRIBUTING.md +84 -0
- Dockerfile +14 -0
- LICENSE +202 -0
- MAINTAINERS.md +9 -0
- README.md +10 -0
- SECURITY.md +17 -0
- app.py +127 -0
- config.py +38 -0
- control/recommendation_handler.py +472 -0
- customize/customize_embeddings.py +49 -0
- customize/customize_helper.py +129 -0
- front_log.json +0 -0
- helpers/authenticate_api.py +49 -0
- helpers/get_credentials.py +63 -0
- helpers/save_model.py +60 -0
- models/.DS_Store +3 -0
- models/all-MiniLM-L6-v2/1_Pooling/config.json +3 -0
- models/all-MiniLM-L6-v2/README.md +3 -0
- models/all-MiniLM-L6-v2/config.json +3 -0
- models/all-MiniLM-L6-v2/config_sentence_transformers.json +3 -0
- models/all-MiniLM-L6-v2/model.safetensors +3 -0
- models/all-MiniLM-L6-v2/modules.json +3 -0
- models/all-MiniLM-L6-v2/sentence_bert_config.json +3 -0
- models/all-MiniLM-L6-v2/special_tokens_map.json +3 -0
- models/all-MiniLM-L6-v2/tokenizer.json +3 -0
- models/all-MiniLM-L6-v2/tokenizer_config.json +3 -0
- models/all-MiniLM-L6-v2/vocab.txt +3 -0
- models/umap/.DS_Store +3 -0
- models/umap/BAAI/bge-large-en-v1.5/encoder.keras +3 -0
- models/umap/BAAI/bge-large-en-v1.5/model.pkl +3 -0
- models/umap/BAAI/bge-large-en-v1.5/parametric_model.keras +3 -0
- models/umap/intfloat/multilingual-e5-large/encoder.keras +3 -0
- models/umap/intfloat/multilingual-e5-large/model.pkl +3 -0
- models/umap/intfloat/multilingual-e5-large/parametric_model.keras +3 -0
- models/umap/sentence-transformers/all-MiniLM-L6-v2/encoder.keras +3 -0
- models/umap/sentence-transformers/all-MiniLM-L6-v2/model.pkl +3 -0
- models/umap/sentence-transformers/all-MiniLM-L6-v2/parametric_model.keras +3 -0
- prompt-sentences-main/README.md +3 -0
- prompt-sentences-main/prompt_sentences-all-minilm-l6-v2.json +3 -0
- prompt-sentences-main/prompt_sentences-bge-large-en-v1.5.json +3 -0
- prompt-sentences-main/prompt_sentences-multilingual-e5-large.json +3 -0
- prompt-sentences-main/prompt_sentences.json +3 -0
- prompt-sentences-main/sentences_by_values-all-minilm-l6-v2.png +3 -0
- prompt-sentences-main/sentences_by_values-bge-large-en-v1.5.png +3 -0
- prompt-sentences-main/sentences_by_values-multilingual-e5-large.png +3 -0
- red-team/README.md +46 -0
.DS_Store
ADDED
Binary file (10.2 kB). View file
|
|
.gitattributes
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
models/** filter=lfs diff=lfs merge=lfs -text
|
2 |
+
prompt-sentences-main/** filter=lfs diff=lfs merge=lfs -text
|
CHANGELOG.md
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Changelog
|
2 |
+
|
3 |
+
All notable changes to this project will be documented in this file.
|
4 |
+
|
5 |
+
## [Unreleased]
|
6 |
+
|
7 |
+
## [0.0.1] - 2019-02-15
|
8 |
+
|
9 |
+
### Added
|
10 |
+
- Added a changelog
|
11 |
+
|
12 |
+
[unreleased]: https://github.com/ibm/repo-template/compare/v0.0.1...HEAD
|
13 |
+
[0.0.1]: https://github.com/ibm/repo-template/releases/tag/v0.0.1
|
CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Contributor Covenant Code of Conduct
|
2 |
+
|
3 |
+
## Our Pledge
|
4 |
+
|
5 |
+
In the interest of fostering an open and welcoming environment, we as
|
6 |
+
contributors and maintainers pledge to making participation in our project and
|
7 |
+
our community a harassment-free experience for everyone, regardless of age, body
|
8 |
+
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
9 |
+
level of experience, education, socio-economic status, nationality, personal
|
10 |
+
appearance, race, religion, or sexual identity and orientation.
|
11 |
+
|
12 |
+
## Our Standards
|
13 |
+
|
14 |
+
Examples of behavior that contributes to creating a positive environment
|
15 |
+
include:
|
16 |
+
|
17 |
+
* Using welcoming and inclusive language
|
18 |
+
* Being respectful of differing viewpoints and experiences
|
19 |
+
* Gracefully accepting constructive criticism
|
20 |
+
* Focusing on what is best for the community
|
21 |
+
* Showing empathy towards other community members
|
22 |
+
|
23 |
+
Examples of unacceptable behavior by participants include:
|
24 |
+
|
25 |
+
* The use of sexualized language or imagery and unwelcome sexual attention or
|
26 |
+
advances
|
27 |
+
* Trolling, insulting/derogatory comments, and personal or political attacks
|
28 |
+
* Public or private harassment
|
29 |
+
* Publishing others' private information, such as a physical or electronic
|
30 |
+
address, without explicit permission
|
31 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
32 |
+
professional setting
|
33 |
+
|
34 |
+
## Our Responsibilities
|
35 |
+
|
36 |
+
Project maintainers are responsible for clarifying the standards of acceptable
|
37 |
+
behavior and are expected to take appropriate and fair corrective action in
|
38 |
+
response to any instances of unacceptable behavior.
|
39 |
+
|
40 |
+
Project maintainers have the right and responsibility to remove, edit, or
|
41 |
+
reject comments, commits, code, wiki edits, issues, and other contributions
|
42 |
+
that are not aligned to this Code of Conduct, or to ban temporarily or
|
43 |
+
permanently any contributor for other behaviors that they deem inappropriate,
|
44 |
+
threatening, offensive, or harmful.
|
45 |
+
|
46 |
+
## Scope
|
47 |
+
|
48 |
+
This Code of Conduct applies both within project spaces and in public spaces
|
49 |
+
when an individual is representing the project or its community. Examples of
|
50 |
+
representing a project or community include using an official project e-mail
|
51 |
+
address, posting via an official social media account, or acting as an appointed
|
52 |
+
representative at an online or offline event. Representation of a project may be
|
53 |
+
further defined and clarified by project maintainers.
|
54 |
+
|
55 |
+
## Enforcement
|
56 |
+
|
57 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
58 |
+
reported by contacting the [project team](./MAINTAINERS.md). All
|
59 |
+
complaints will be reviewed and investigated and will result in a response that
|
60 |
+
is deemed necessary and appropriate to the circumstances. The project team is
|
61 |
+
obligated to maintain confidentiality with regard to the reporter of an incident.
|
62 |
+
Further details of specific enforcement policies may be posted separately.
|
63 |
+
|
64 |
+
Project maintainers who do not follow or enforce the Code of Conduct in good
|
65 |
+
faith may face temporary or permanent repercussions as determined by other
|
66 |
+
members of the project's leadership.
|
67 |
+
|
68 |
+
## Attribution
|
69 |
+
|
70 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
71 |
+
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
72 |
+
|
73 |
+
[homepage]: https://www.contributor-covenant.org
|
74 |
+
|
75 |
+
For answers to common questions about this code of conduct, see
|
76 |
+
https://www.contributor-covenant.org/faq
|
CONTRIBUTING.md
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Contributing In General
|
2 |
+
Our project welcomes external contributions. If you have an itch, please feel
|
3 |
+
free to scratch it.
|
4 |
+
|
5 |
+
To contribute code or documentation, please submit a **FIXME** [pull request](https://github.com/ibm/repo-template/pulls).
|
6 |
+
|
7 |
+
A good way to familiarize yourself with the codebase and contribution process is
|
8 |
+
to look for and tackle low-hanging fruit in the **FIXME** [issue tracker](https://github.com/ibm/repo-template/issues).
|
9 |
+
Before embarking on a more ambitious contribution, please quickly [get in touch](#communication) with us.
|
10 |
+
|
11 |
+
**Note: We appreciate your effort, and want to avoid a situation where a contribution
|
12 |
+
requires extensive rework (by you or by us), sits in backlog for a long time, or
|
13 |
+
cannot be accepted at all!**
|
14 |
+
|
15 |
+
### Proposing new features
|
16 |
+
|
17 |
+
If you would like to implement a new feature, please **FIXME** [raise an issue](https://github.com/ibm/repo-template/issues)
|
18 |
+
before sending a pull request so the feature can be discussed. This is to avoid
|
19 |
+
you wasting your valuable time working on a feature that the project developers
|
20 |
+
are not interested in accepting into the code base.
|
21 |
+
|
22 |
+
### Fixing bugs
|
23 |
+
|
24 |
+
If you would like to fix a bug, please **FIXME** [raise an issue](https://github.com/ibm/repo-template/issues) before sending a
|
25 |
+
pull request so it can be tracked.
|
26 |
+
|
27 |
+
### Merge approval
|
28 |
+
|
29 |
+
The project maintainers use LGTM (Looks Good To Me) in comments on the code
|
30 |
+
review to indicate acceptance. A change requires LGTMs from two of the
|
31 |
+
maintainers of each component affected.
|
32 |
+
|
33 |
+
For a list of the maintainers, see the [MAINTAINERS.md](MAINTAINERS.md) page.
|
34 |
+
|
35 |
+
## Legal
|
36 |
+
|
37 |
+
Each source file must include a license header for the Apache
|
38 |
+
Software License 2.0. Using the SPDX format is the simplest approach.
|
39 |
+
e.g.
|
40 |
+
|
41 |
+
```
|
42 |
+
/*
|
43 |
+
Copyright <holder> All Rights Reserved.
|
44 |
+
|
45 |
+
SPDX-License-Identifier: Apache-2.0
|
46 |
+
*/
|
47 |
+
```
|
48 |
+
|
49 |
+
We have tried to make it as easy as possible to make contributions. This
|
50 |
+
applies to how we handle the legal aspects of contribution. We use the
|
51 |
+
same approach - the [Developer's Certificate of Origin 1.1 (DCO)](https://github.com/hyperledger/fabric/blob/master/docs/source/DCO1.1.txt) - that the Linux® Kernel [community](https://elinux.org/Developer_Certificate_Of_Origin)
|
52 |
+
uses to manage code contributions.
|
53 |
+
|
54 |
+
We simply ask that when submitting a patch for review, the developer
|
55 |
+
must include a sign-off statement in the commit message.
|
56 |
+
|
57 |
+
Here is an example Signed-off-by line, which indicates that the
|
58 |
+
submitter accepts the DCO:
|
59 |
+
|
60 |
+
```
|
61 |
+
Signed-off-by: John Doe <john.doe@example.com>
|
62 |
+
```
|
63 |
+
|
64 |
+
You can include this automatically when you commit a change to your
|
65 |
+
local git repository using the following command:
|
66 |
+
|
67 |
+
```
|
68 |
+
git commit -s
|
69 |
+
```
|
70 |
+
|
71 |
+
## Communication
|
72 |
+
**FIXME** Please feel free to connect with us on our [Slack channel](link).
|
73 |
+
|
74 |
+
## Setup
|
75 |
+
**FIXME** Please add any special setup instructions for your project to help the developer
|
76 |
+
become productive quickly.
|
77 |
+
|
78 |
+
## Testing
|
79 |
+
**FIXME** Please provide information that helps the developer test any changes they make
|
80 |
+
before submitting.
|
81 |
+
|
82 |
+
## Coding style guidelines
|
83 |
+
**FIXME** Optional, but recommended: please share any specific style guidelines you might
|
84 |
+
have for your project.
|
Dockerfile
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.9
|
2 |
+
|
3 |
+
RUN useradd -m -u 1000 user
|
4 |
+
USER user
|
5 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
6 |
+
|
7 |
+
WORKDIR /app
|
8 |
+
|
9 |
+
COPY --chown=user ./requirements.txt requirements.txt
|
10 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
11 |
+
|
12 |
+
COPY --chown=user . /app
|
13 |
+
|
14 |
+
CMD ["python", "app.py", "--host", "0.0.0.0", "--port", "7860"]
|
LICENSE
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright {yyyy} {name of copyright owner}
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
202 |
+
|
MAINTAINERS.md
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# MAINTAINERS
|
2 |
+
|
3 |
+
Mo McElaney - mmcelaney@us.ibm.com
|
4 |
+
|
5 |
+
JJ Asghar - jja@ibm.com
|
6 |
+
|
7 |
+
Joe Sepi - joesepi@ibm.com
|
8 |
+
|
9 |
+
Brad Topol - btopol@us.ibm.com
|
README.md
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Resapi
|
3 |
+
emoji: 🐢
|
4 |
+
colorFrom: gray
|
5 |
+
colorTo: red
|
6 |
+
sdk: docker
|
7 |
+
pinned: false
|
8 |
+
---
|
9 |
+
|
10 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
SECURITY.md
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Security Policy
|
2 |
+
|
3 |
+
## Supported Versions
|
4 |
+
|
5 |
+
Use this section to tell people about which versions of your project are
|
6 |
+
currently being supported with security updates.
|
7 |
+
|
8 |
+
| Version | Supported |
|
9 |
+
| ------- | ------------------ |
|
10 |
+
| 5.1.x | :white_check_mark: |
|
11 |
+
| 5.0.x | :x: |
|
12 |
+
| 4.0.x | :white_check_mark: |
|
13 |
+
| < 4.0 | :x: |
|
14 |
+
|
15 |
+
## Reporting a Vulnerability
|
16 |
+
|
17 |
+
To report a security issue, please email $VMTalias with a description of the issue, the steps you took to create the issue, affected versions, and if known, mitigations for the issue. Our vulnerability management team will acknowledge receiving your email within 3 working days. This project follows a 90 day disclosure timeline.
|
app.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
# Copyright 2021, IBM Corporation.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""
|
19 |
+
Flask API app and routes.
|
20 |
+
"""
|
21 |
+
|
22 |
+
__author__ = "Vagner Santana, Melina Alberio, Cassia Sanctos and Tiago Machado"
|
23 |
+
__copyright__ = "IBM Corporation 2024"
|
24 |
+
__credits__ = ["Vagner Santana, Melina Alberio, Cassia Sanctos, Tiago Machado"]
|
25 |
+
__license__ = "Apache 2.0"
|
26 |
+
__version__ = "0.0.1"
|
27 |
+
|
28 |
+
|
29 |
+
from flask import Flask, request, jsonify
|
30 |
+
from flask_cors import CORS, cross_origin
|
31 |
+
from flask_restful import Resource, Api, reqparse
|
32 |
+
import control.recommendation_handler as recommendation_handler
|
33 |
+
from helpers import get_credentials, authenticate_api, save_model
|
34 |
+
import config as cfg
|
35 |
+
import logging
|
36 |
+
import uuid
|
37 |
+
import json
|
38 |
+
import os
|
39 |
+
|
40 |
+
app = Flask(__name__)
|
41 |
+
|
42 |
+
# configure logging
|
43 |
+
logging.basicConfig(
|
44 |
+
filename='app.log', # Log file name
|
45 |
+
level=logging.INFO, # Log level (INFO, DEBUG, WARNING, ERROR, CRITICAL)
|
46 |
+
format='%(asctime)s - %(levelname)s - %(message)s' # Log message format
|
47 |
+
)
|
48 |
+
|
49 |
+
# access the app's logger
|
50 |
+
logger = app.logger
|
51 |
+
# create user id
|
52 |
+
id = str(uuid.uuid4())
|
53 |
+
|
54 |
+
# swagger configs
|
55 |
+
app.register_blueprint(cfg.SWAGGER_BLUEPRINT, url_prefix = cfg.SWAGGER_URL)
|
56 |
+
FRONT_LOG_FILE = 'front_log.json'
|
57 |
+
|
58 |
+
|
59 |
+
@app.route("/")
|
60 |
+
def index():
|
61 |
+
user_ip = request.remote_addr
|
62 |
+
logger.info(f'USER {user_ip} - ID {id} - started the app')
|
63 |
+
return "Ready!"
|
64 |
+
|
65 |
+
@app.route("/recommend", methods=['GET'])
|
66 |
+
@cross_origin()
|
67 |
+
def recommend():
|
68 |
+
user_ip = request.remote_addr
|
69 |
+
hf_token, hf_url = get_credentials.get_credentials()
|
70 |
+
api_url, headers = authenticate_api.authenticate_api(hf_token, hf_url)
|
71 |
+
prompt_json = recommendation_handler.populate_json()
|
72 |
+
args = request.args
|
73 |
+
prompt = args.get("prompt")
|
74 |
+
recommendation_json = recommendation_handler.recommend_prompt(prompt, prompt_json,
|
75 |
+
api_url, headers)
|
76 |
+
logger.info(f'USER - {user_ip} - ID {id} - accessed recommend route')
|
77 |
+
logger.info(f'RECOMMEND ROUTE - request: {prompt} response: {recommendation_json}')
|
78 |
+
return recommendation_json
|
79 |
+
|
80 |
+
@app.route("/get_thresholds", methods=['GET'])
|
81 |
+
@cross_origin()
|
82 |
+
def get_thresholds():
|
83 |
+
hf_token, hf_url = get_credentials.get_credentials()
|
84 |
+
api_url, headers = authenticate_api.authenticate_api(hf_token, hf_url)
|
85 |
+
prompt_json = recommendation_handler.populate_json()
|
86 |
+
model_id = 'sentence-transformers/all-minilm-l6-v2'
|
87 |
+
args = request.args
|
88 |
+
#print("args list = ", args)
|
89 |
+
prompt = args.get("prompt")
|
90 |
+
thresholds_json = recommendation_handler.get_thresholds(prompt, prompt_json, api_url,
|
91 |
+
headers, model_id)
|
92 |
+
return thresholds_json
|
93 |
+
|
94 |
+
@app.route("/recommend_local", methods=['GET'])
|
95 |
+
@cross_origin()
|
96 |
+
def recommend_local():
|
97 |
+
model_id, model_path = save_model.save_model()
|
98 |
+
prompt_json = recommendation_handler.populate_json()
|
99 |
+
args = request.args
|
100 |
+
print("args list = ", args)
|
101 |
+
prompt = args.get("prompt")
|
102 |
+
local_recommendation_json = recommendation_handler.recommend_local(prompt, prompt_json,
|
103 |
+
model_id, model_path)
|
104 |
+
return local_recommendation_json
|
105 |
+
|
106 |
+
@app.route("/log", methods=['POST'])
|
107 |
+
@cross_origin()
|
108 |
+
def log():
|
109 |
+
f_path = 'static/demo/log/'
|
110 |
+
new_data = request.get_json()
|
111 |
+
|
112 |
+
try:
|
113 |
+
with open(f_path+FRONT_LOG_FILE, 'r') as f:
|
114 |
+
existing_data = json.load(f)
|
115 |
+
except FileNotFoundError:
|
116 |
+
existing_data = []
|
117 |
+
|
118 |
+
existing_data.update(new_data)
|
119 |
+
|
120 |
+
#log_data = request.json
|
121 |
+
with open(f_path+FRONT_LOG_FILE, 'w') as f:
|
122 |
+
json.dump(existing_data, f)
|
123 |
+
return jsonify({'message': 'Data added successfully', 'data': existing_data}), 201
|
124 |
+
|
125 |
+
if __name__=='__main__':
|
126 |
+
debug_mode = os.getenv('FLASK_DEBUG', 'False').lower() in ['true', '1', 't']
|
127 |
+
app.run(host='0.0.0.0', port='8080', debug=debug_mode)
|
config.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
# Copyright 2021, IBM Corporation.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""
|
19 |
+
Swagger configuration.
|
20 |
+
"""
|
21 |
+
|
22 |
+
__author__ = "Vagner Santana, Melina Alberio, Cassia Sanctos and Tiago Machado"
|
23 |
+
__copyright__ = "IBM Corporation 2024"
|
24 |
+
__credits__ = ["Vagner Santana, Melina Alberio, Cassia Sanctos, Tiago Machado"]
|
25 |
+
__license__ = "Apache 2.0"
|
26 |
+
__version__ = "0.0.1"
|
27 |
+
|
28 |
+
from flask_swagger_ui import get_swaggerui_blueprint
|
29 |
+
|
30 |
+
SWAGGER_URL = '/swagger'
|
31 |
+
API_URL = '/static/swagger.json'
|
32 |
+
SWAGGER_BLUEPRINT = get_swaggerui_blueprint(
|
33 |
+
SWAGGER_URL,
|
34 |
+
API_URL,
|
35 |
+
config={
|
36 |
+
'app_name': "Prompt Recommendation API"
|
37 |
+
}
|
38 |
+
)
|
control/recommendation_handler.py
ADDED
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
# Copyright 2021, IBM Corporation.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""
|
19 |
+
Python lib to recommend prompts.
|
20 |
+
"""
|
21 |
+
|
22 |
+
__author__ = "Vagner Santana, Melina Alberio, Cassia Sanctos and Tiago Machado"
|
23 |
+
__copyright__ = "IBM Corporation 2024"
|
24 |
+
__credits__ = ["Vagner Santana, Melina Alberio, Cassia Sanctos, Tiago Machado"]
|
25 |
+
__license__ = "Apache 2.0"
|
26 |
+
__version__ = "0.0.1"
|
27 |
+
|
28 |
+
import requests
|
29 |
+
import json
|
30 |
+
import math
|
31 |
+
import re
|
32 |
+
import warnings
|
33 |
+
import pandas as pd
|
34 |
+
import numpy as np
|
35 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
36 |
+
import os
|
37 |
+
#os.environ['TRANSFORMERS_CACHE'] ="./models/allmini/cache"
|
38 |
+
import os.path
|
39 |
+
from sentence_transformers import SentenceTransformer
|
40 |
+
from umap import UMAP
|
41 |
+
import tensorflow as tf
|
42 |
+
from umap.parametric_umap import ParametricUMAP, load_ParametricUMAP
|
43 |
+
from sentence_transformers import SentenceTransformer
|
44 |
+
|
45 |
+
def populate_json(json_file_path = './prompt-sentences-main/prompt_sentences-all-minilm-l6-v2.json',
|
46 |
+
existing_json_populated_file_path = './prompt-sentences-main/prompt_sentences-all-minilm-l6-v2.json'):
|
47 |
+
"""
|
48 |
+
Function that receives a default json file with
|
49 |
+
empty embeddings and checks whether there is a
|
50 |
+
partially populated json file.
|
51 |
+
|
52 |
+
Args:
|
53 |
+
json_file_path: Path to json default file with
|
54 |
+
empty embeddings.
|
55 |
+
existing_json_populated_file_path: Path to partially
|
56 |
+
populated json file.
|
57 |
+
|
58 |
+
Returns:
|
59 |
+
A json.
|
60 |
+
|
61 |
+
Raises:
|
62 |
+
Exception when json file can't be loaded.
|
63 |
+
"""
|
64 |
+
json_file = json_file_path
|
65 |
+
if(os.path.isfile(existing_json_populated_file_path)):
|
66 |
+
json_file = existing_json_populated_file_path
|
67 |
+
try:
|
68 |
+
prompt_json = json.load(open(json_file))
|
69 |
+
json_error = None
|
70 |
+
return prompt_json, json_error
|
71 |
+
except Exception as e:
|
72 |
+
json_error = e
|
73 |
+
print(f'Error when loading sentences json file: {json_error}')
|
74 |
+
prompt_json = None
|
75 |
+
return prompt_json, json_error
|
76 |
+
|
77 |
+
def query(texts, api_url, headers):
|
78 |
+
"""
|
79 |
+
Function that requests embeddings for a given sentence.
|
80 |
+
|
81 |
+
Args:
|
82 |
+
texts: The sentence or entered prompt text.
|
83 |
+
api_url: API url for HF request.
|
84 |
+
headers: Content headers for HF request.
|
85 |
+
|
86 |
+
Returns:
|
87 |
+
A json with the sentence embeddings.
|
88 |
+
|
89 |
+
Raises:
|
90 |
+
Warning: Warns about sentences that have more
|
91 |
+
than 256 words.
|
92 |
+
"""
|
93 |
+
for t in texts:
|
94 |
+
n_words = len(re.split(r"\s+", t))
|
95 |
+
if(n_words > 256):
|
96 |
+
# warning in case of prompts longer than 256 words
|
97 |
+
warnings.warn("Warning: Sentence provided is longer than 256 words. Model all-MiniLM-L6-v2 expects sentences up to 256 words.")
|
98 |
+
warnings.warn("Word count:{}".format(n_words))
|
99 |
+
if('sentence-transformers/all-MiniLM-L6-v2' in api_url):
|
100 |
+
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
101 |
+
out = model.encode(texts).tolist()
|
102 |
+
else:
|
103 |
+
response = requests.post(api_url, headers=headers, json={"inputs": texts, "options":{"wait_for_model":True}})
|
104 |
+
out = response.json()
|
105 |
+
return out
|
106 |
+
|
107 |
+
def split_into_sentences(prompt):
|
108 |
+
"""
|
109 |
+
Function that splits the input text into sentences based
|
110 |
+
on punctuation (.!?). The regular expression pattern
|
111 |
+
'(?<=[.!?]) +' ensures that we split after a sentence-ending
|
112 |
+
punctuation followed by one or more spaces.
|
113 |
+
|
114 |
+
Args:
|
115 |
+
prompt: The entered prompt text.
|
116 |
+
|
117 |
+
Returns:
|
118 |
+
A list of extracted sentences.
|
119 |
+
|
120 |
+
Raises:
|
121 |
+
Nothing.
|
122 |
+
"""
|
123 |
+
sentences = re.split(r'(?<=[.!?]) +', prompt)
|
124 |
+
return sentences
|
125 |
+
|
126 |
+
|
127 |
+
def get_similarity(embedding1, embedding2):
|
128 |
+
"""
|
129 |
+
Function that returns cosine similarity between
|
130 |
+
two embeddings.
|
131 |
+
|
132 |
+
Args:
|
133 |
+
embedding1: first embedding.
|
134 |
+
embedding2: second embedding.
|
135 |
+
|
136 |
+
Returns:
|
137 |
+
The similarity value.
|
138 |
+
|
139 |
+
Raises:
|
140 |
+
Nothing.
|
141 |
+
"""
|
142 |
+
v1 = np.array( embedding1 ).reshape( 1, -1 )
|
143 |
+
v2 = np.array( embedding2 ).reshape( 1, -1 )
|
144 |
+
similarity = cosine_similarity( v1, v2 )
|
145 |
+
return similarity[0, 0]
|
146 |
+
|
147 |
+
def get_distance(embedding1, embedding2):
|
148 |
+
"""
|
149 |
+
Function that returns euclidean distance between
|
150 |
+
two embeddings.
|
151 |
+
|
152 |
+
Args:
|
153 |
+
embedding1: first embedding.
|
154 |
+
embedding2: second embedding.
|
155 |
+
|
156 |
+
Returns:
|
157 |
+
The euclidean distance value.
|
158 |
+
|
159 |
+
Raises:
|
160 |
+
Nothing.
|
161 |
+
"""
|
162 |
+
total = 0
|
163 |
+
if(len(embedding1) != len(embedding2)):
|
164 |
+
return math.inf
|
165 |
+
for i, obj in enumerate(embedding1):
|
166 |
+
total += math.pow(embedding2[0][i] - embedding1[0][i], 2)
|
167 |
+
return(math.sqrt(total))
|
168 |
+
|
169 |
+
def sort_by_similarity(e):
|
170 |
+
"""
|
171 |
+
Function that sorts by similarity.
|
172 |
+
|
173 |
+
Args:
|
174 |
+
e:
|
175 |
+
|
176 |
+
Returns:
|
177 |
+
The sorted similarity value.
|
178 |
+
|
179 |
+
Raises:
|
180 |
+
Nothing.
|
181 |
+
"""
|
182 |
+
return e['similarity']
|
183 |
+
|
184 |
+
def recommend_prompt(prompt, prompt_json, api_url, headers, add_lower_threshold = 0.3,
|
185 |
+
add_upper_threshold = 0.5, remove_lower_threshold = 0.1,
|
186 |
+
remove_upper_threshold = 0.5, model_id = 'sentence-transformers/all-minilm-l6-v2'):
|
187 |
+
"""
|
188 |
+
Function that recommends prompts additions or removals.
|
189 |
+
|
190 |
+
Args:
|
191 |
+
prompt: The entered prompt text.
|
192 |
+
prompt_json: Json file populated with embeddings.
|
193 |
+
api_url: API url for HF request.
|
194 |
+
headers: Content headers for HF request.
|
195 |
+
add_lower_threshold: Lower threshold for sentence addition,
|
196 |
+
the default value is 0.3.
|
197 |
+
add_upper_threshold: Upper threshold for sentence addition,
|
198 |
+
the default value is 0.5.
|
199 |
+
remove_lower_threshold: Lower threshold for sentence removal,
|
200 |
+
the default value is 0.3.
|
201 |
+
remove_upper_threshold: Upper threshold for sentence removal,
|
202 |
+
the default value is 0.5.
|
203 |
+
model_id: Id of the model, the default value is all-minilm-l6-v2 movel.
|
204 |
+
|
205 |
+
Returns:
|
206 |
+
Prompt values to add or remove.
|
207 |
+
|
208 |
+
Raises:
|
209 |
+
Nothing.
|
210 |
+
"""
|
211 |
+
if(model_id == 'baai/bge-large-en-v1.5' ):
|
212 |
+
json_file = './prompt-sentences-main/prompt_sentences-bge-large-en-v1.5.json'
|
213 |
+
umap_model = load_ParametricUMAP('./models/umap/BAAI/bge-large-en-v1.5/')
|
214 |
+
elif(model_id == 'intfloat/multilingual-e5-large'):
|
215 |
+
json_file = './prompt-sentences-main/prompt_sentences-multilingual-e5-large.json'
|
216 |
+
umap_model = load_ParametricUMAP('./models/umap/intfloat/multilingual-e5-large/')
|
217 |
+
else: # fall back to all-minilm as default
|
218 |
+
json_file = './prompt-sentences-main/prompt_sentences-all-minilm-l6-v2.json'
|
219 |
+
umap_model = load_ParametricUMAP('./models/umap/sentence-transformers/all-MiniLM-L6-v2/')
|
220 |
+
|
221 |
+
prompt_json = json.load(open(json_file))
|
222 |
+
|
223 |
+
# Output initialization
|
224 |
+
out, out['input'], out['add'], out['remove'] = {}, {}, {}, {}
|
225 |
+
input_items, items_to_add, items_to_remove = [], [], []
|
226 |
+
|
227 |
+
# Spliting prompt into sentences
|
228 |
+
input_sentences = split_into_sentences(prompt)
|
229 |
+
|
230 |
+
# TODO: Request embeddings for input an d store in a input_embeddingS
|
231 |
+
|
232 |
+
# Recommendation of values to add to the current prompt
|
233 |
+
# Using only the last sentence for the add recommendation
|
234 |
+
input_embedding = query(input_sentences[-1], api_url, headers)
|
235 |
+
for v in prompt_json['positive_values']:
|
236 |
+
# Dealing with values without prompts and makinig sure they have the same dimensions
|
237 |
+
if(len(v['centroid']) == len(input_embedding)):
|
238 |
+
if(get_similarity(pd.DataFrame(input_embedding), pd.DataFrame(v['centroid'])) > add_lower_threshold):
|
239 |
+
closer_prompt = -1
|
240 |
+
for p in v['prompts']:
|
241 |
+
d_prompt = get_similarity(pd.DataFrame(input_embedding), pd.DataFrame(p['embedding']))
|
242 |
+
# The sentence_threshold is being used as a ceiling meaning that for high similarities the sentence/value might already be presente in the prompt
|
243 |
+
# So, we don't want to recommend adding something that is already there
|
244 |
+
if(d_prompt > closer_prompt and d_prompt > add_lower_threshold and d_prompt < add_upper_threshold):
|
245 |
+
closer_prompt = d_prompt
|
246 |
+
items_to_add.append({
|
247 |
+
'value': v['label'],
|
248 |
+
'prompt': p['text'],
|
249 |
+
'similarity': d_prompt,
|
250 |
+
'x': p['x'],
|
251 |
+
'y': p['y']})
|
252 |
+
out['add'] = items_to_add
|
253 |
+
|
254 |
+
# Recommendation of values to remove from the current prompt
|
255 |
+
i = 0
|
256 |
+
|
257 |
+
# Recommendation of values to remove from the current prompt
|
258 |
+
for sentence in input_sentences:
|
259 |
+
input_embedding = query(sentence, api_url, headers) # remote
|
260 |
+
# Obtaining XY coords for input sentences from a parametric UMAP model
|
261 |
+
if(len(prompt_json['negative_values'][0]['centroid']) == len(input_embedding) and sentence != ''):
|
262 |
+
embeddings_umap = umap_model.transform(tf.expand_dims(pd.DataFrame(input_embedding), axis=0))
|
263 |
+
input_items.append({
|
264 |
+
'sentence': sentence,
|
265 |
+
'x': str(embeddings_umap[0][0]),
|
266 |
+
'y': str(embeddings_umap[0][1])
|
267 |
+
})
|
268 |
+
|
269 |
+
for v in prompt_json['negative_values']:
|
270 |
+
# Dealing with values without prompts and makinig sure they have the same dimensions
|
271 |
+
if(len(v['centroid']) == len(input_embedding)):
|
272 |
+
if(get_similarity(pd.DataFrame(input_embedding), pd.DataFrame(v['centroid'])) > remove_lower_threshold):
|
273 |
+
closer_prompt = -1
|
274 |
+
for p in v['prompts']:
|
275 |
+
d_prompt = get_similarity(pd.DataFrame(input_embedding), pd.DataFrame(p['embedding']))
|
276 |
+
# A more restrict threshold is used here to prevent false positives
|
277 |
+
# The sentence_threshold is being used to indicate that there must be a sentence in the prompt that is similiar to one of our adversarial prompts
|
278 |
+
# So, yes, we want to recommend the removal of something adversarial we've found
|
279 |
+
if(d_prompt > closer_prompt and d_prompt > remove_upper_threshold):
|
280 |
+
closer_prompt = d_prompt
|
281 |
+
items_to_remove.append({
|
282 |
+
'value': v['label'],
|
283 |
+
'sentence': sentence,
|
284 |
+
'sentence_index': i,
|
285 |
+
'closest_harmful_sentence': p['text'],
|
286 |
+
'similarity': d_prompt,
|
287 |
+
'x': p['x'],
|
288 |
+
'y': p['y']})
|
289 |
+
out['remove'] = items_to_remove
|
290 |
+
i += 1
|
291 |
+
|
292 |
+
out['input'] = input_items
|
293 |
+
|
294 |
+
out['add'] = sorted(out['add'], key=sort_by_similarity, reverse=True)
|
295 |
+
values_map = {}
|
296 |
+
for item in out['add'][:]:
|
297 |
+
if(item['value'] in values_map):
|
298 |
+
out['add'].remove(item)
|
299 |
+
else:
|
300 |
+
values_map[item['value']] = item['similarity']
|
301 |
+
out['add'] = out['add'][0:5]
|
302 |
+
|
303 |
+
out['remove'] = sorted(out['remove'], key=sort_by_similarity, reverse=True)
|
304 |
+
values_map = {}
|
305 |
+
for item in out['remove'][:]:
|
306 |
+
if(item['value'] in values_map):
|
307 |
+
out['remove'].remove(item)
|
308 |
+
else:
|
309 |
+
values_map[item['value']] = item['similarity']
|
310 |
+
out['remove'] = out['remove'][0:5]
|
311 |
+
return out
|
312 |
+
|
313 |
+
def get_thresholds(prompts, prompt_json, api_url, headers, model_id = 'sentence-transformers/all-minilm-l6-v2'):
|
314 |
+
"""
|
315 |
+
Function that recommends thresholds given an array of prompts.
|
316 |
+
|
317 |
+
Args:
|
318 |
+
prompts: The array with samples of prompts to be used in the system.
|
319 |
+
prompt_json: Sentences to be forwarded to the recommendation endpoint.
|
320 |
+
model_id: Id of the model, the default value is all-minilm-l6-v2 model.
|
321 |
+
|
322 |
+
Returns:
|
323 |
+
A map with thresholds for the sample prompts and the informed model.
|
324 |
+
|
325 |
+
Raises:
|
326 |
+
Nothing.
|
327 |
+
"""
|
328 |
+
# Array limits for retrieving the thresholds
|
329 |
+
# if( len( prompts ) < 10 or len( prompts ) > 30 ):
|
330 |
+
# return -1
|
331 |
+
add_similarities = []
|
332 |
+
remove_similarities = []
|
333 |
+
|
334 |
+
for p_id, p in enumerate(prompts):
|
335 |
+
out = recommend_prompt(p, prompt_json, api_url, headers, 0, 1, 0, 0, model_id) # Wider possible range
|
336 |
+
|
337 |
+
for r in out['add']:
|
338 |
+
add_similarities.append(r['similarity'])
|
339 |
+
for r in out['remove']:
|
340 |
+
remove_similarities.append(r['similarity'])
|
341 |
+
|
342 |
+
add_similarities_df = pd.DataFrame({'similarity': add_similarities})
|
343 |
+
remove_similarities_df = pd.DataFrame({'similarity': remove_similarities})
|
344 |
+
|
345 |
+
thresholds = {}
|
346 |
+
thresholds['add_lower_threshold'] = round(add_similarities_df.describe([.1]).loc['10%', 'similarity'], 1)
|
347 |
+
thresholds['add_higher_threshold'] = round(add_similarities_df.describe([.9]).loc['90%', 'similarity'], 1)
|
348 |
+
thresholds['remove_lower_threshold'] = round(remove_similarities_df.describe([.1]).loc['10%', 'similarity'], 1)
|
349 |
+
thresholds['remove_higher_threshold'] = round(remove_similarities_df.describe([.9]).loc['90%', 'similarity'], 1)
|
350 |
+
|
351 |
+
return thresholds
|
352 |
+
|
353 |
+
def recommend_local(prompt, prompt_json, model_id, model_path = './models/all-MiniLM-L6-v2/', add_lower_threshold = 0.3,
|
354 |
+
add_upper_threshold = 0.5, remove_lower_threshold = 0.1,
|
355 |
+
remove_upper_threshold = 0.5):
|
356 |
+
"""
|
357 |
+
Function that recommends prompts additions or removals
|
358 |
+
using a local model.
|
359 |
+
|
360 |
+
Args:
|
361 |
+
prompt: The entered prompt text.
|
362 |
+
prompt_json: Json file populated with embeddings.
|
363 |
+
model_id: Id of the local model.
|
364 |
+
model_path: Path to the local model.
|
365 |
+
|
366 |
+
Returns:
|
367 |
+
Prompt values to add or remove.
|
368 |
+
|
369 |
+
Raises:
|
370 |
+
Nothing.
|
371 |
+
"""
|
372 |
+
if(model_id == 'baai/bge-large-en-v1.5' ):
|
373 |
+
json_file = './prompt-sentences-main/prompt_sentences-bge-large-en-v1.5.json'
|
374 |
+
umap_model = load_ParametricUMAP('./models/umap/BAAI/bge-large-en-v1.5/')
|
375 |
+
elif(model_id == 'intfloat/multilingual-e5-large'):
|
376 |
+
json_file = './prompt-sentences-main/prompt_sentences-multilingual-e5-large.json'
|
377 |
+
umap_model = load_ParametricUMAP('./models/umap/intfloat/multilingual-e5-large/')
|
378 |
+
else: # fall back to all-minilm as default
|
379 |
+
json_file = './prompt-sentences-main/prompt_sentences-all-minilm-l6-v2.json'
|
380 |
+
umap_model = load_ParametricUMAP('./models/umap/sentence-transformers/all-MiniLM-L6-v2/')
|
381 |
+
|
382 |
+
prompt_json = json.load(open(json_file))
|
383 |
+
|
384 |
+
# Output initialization
|
385 |
+
out, out['input'], out['add'], out['remove'] = {}, {}, {}, {}
|
386 |
+
input_items, items_to_add, items_to_remove = [], [], []
|
387 |
+
|
388 |
+
# Spliting prompt into sentences
|
389 |
+
input_sentences = split_into_sentences(prompt)
|
390 |
+
|
391 |
+
# Recommendation of values to add to the current prompt
|
392 |
+
# Using only the last sentence for the add recommendation
|
393 |
+
model = SentenceTransformer(model_path)
|
394 |
+
input_embedding = model.encode(input_sentences[-1])
|
395 |
+
|
396 |
+
for v in prompt_json['positive_values']:
|
397 |
+
# Dealing with values without prompts and makinig sure they have the same dimensions
|
398 |
+
if(len(v['centroid']) == len(input_embedding)):
|
399 |
+
if(get_similarity(pd.DataFrame(input_embedding), pd.DataFrame(v['centroid'])) > add_lower_threshold):
|
400 |
+
closer_prompt = -1
|
401 |
+
for p in v['prompts']:
|
402 |
+
d_prompt = get_similarity(pd.DataFrame(input_embedding), pd.DataFrame(p['embedding']))
|
403 |
+
# The sentence_threshold is being used as a ceiling meaning that for high similarities the sentence/value might already be presente in the prompt
|
404 |
+
# So, we don't want to recommend adding something that is already there
|
405 |
+
if(d_prompt > closer_prompt and d_prompt > add_lower_threshold and d_prompt < add_upper_threshold):
|
406 |
+
closer_prompt = d_prompt
|
407 |
+
items_to_add.append({
|
408 |
+
'value': v['label'],
|
409 |
+
'prompt': p['text'],
|
410 |
+
'similarity': d_prompt,
|
411 |
+
'x': p['x'],
|
412 |
+
'y': p['y']})
|
413 |
+
out['add'] = items_to_add
|
414 |
+
|
415 |
+
# Recommendation of values to remove from the current prompt
|
416 |
+
i = 0
|
417 |
+
|
418 |
+
# Recommendation of values to remove from the current prompt
|
419 |
+
for sentence in input_sentences:
|
420 |
+
input_embedding = model.encode(sentence) # local
|
421 |
+
# Obtaining XY coords for input sentences from a parametric UMAP model
|
422 |
+
if(len(prompt_json['negative_values'][0]['centroid']) == len(input_embedding) and sentence != ''):
|
423 |
+
embeddings_umap = umap_model.transform(tf.expand_dims(pd.DataFrame(input_embedding), axis=0))
|
424 |
+
input_items.append({
|
425 |
+
'sentence': sentence,
|
426 |
+
'x': str(embeddings_umap[0][0]),
|
427 |
+
'y': str(embeddings_umap[0][1])
|
428 |
+
})
|
429 |
+
|
430 |
+
for v in prompt_json['negative_values']:
|
431 |
+
# Dealing with values without prompts and makinig sure they have the same dimensions
|
432 |
+
if(len(v['centroid']) == len(input_embedding)):
|
433 |
+
if(get_similarity(pd.DataFrame(input_embedding), pd.DataFrame(v['centroid'])) > remove_lower_threshold):
|
434 |
+
closer_prompt = -1
|
435 |
+
for p in v['prompts']:
|
436 |
+
d_prompt = get_similarity(pd.DataFrame(input_embedding), pd.DataFrame(p['embedding']))
|
437 |
+
# A more restrict threshold is used here to prevent false positives
|
438 |
+
# The sentence_threhold is being used to indicate that there must be a sentence in the prompt that is similiar to one of our adversarial prompts
|
439 |
+
# So, yes, we want to recommend the revolval of something adversarial we've found
|
440 |
+
if(d_prompt > closer_prompt and d_prompt > remove_upper_threshold):
|
441 |
+
closer_prompt = d_prompt
|
442 |
+
items_to_remove.append({
|
443 |
+
'value': v['label'],
|
444 |
+
'sentence': sentence,
|
445 |
+
'sentence_index': i,
|
446 |
+
'closest_harmful_sentence': p['text'],
|
447 |
+
'similarity': d_prompt,
|
448 |
+
'x': p['x'],
|
449 |
+
'y': p['y']})
|
450 |
+
out['remove'] = items_to_remove
|
451 |
+
i += 1
|
452 |
+
|
453 |
+
out['input'] = input_items
|
454 |
+
|
455 |
+
out['add'] = sorted(out['add'], key=sort_by_similarity, reverse=True)
|
456 |
+
values_map = {}
|
457 |
+
for item in out['add'][:]:
|
458 |
+
if(item['value'] in values_map):
|
459 |
+
out['add'].remove(item)
|
460 |
+
else:
|
461 |
+
values_map[item['value']] = item['similarity']
|
462 |
+
out['add'] = out['add'][0:5]
|
463 |
+
|
464 |
+
out['remove'] = sorted(out['remove'], key=sort_by_similarity, reverse=True)
|
465 |
+
values_map = {}
|
466 |
+
for item in out['remove'][:]:
|
467 |
+
if(item['value'] in values_map):
|
468 |
+
out['remove'].remove(item)
|
469 |
+
else:
|
470 |
+
values_map[item['value']] = item['similarity']
|
471 |
+
out['remove'] = out['remove'][0:5]
|
472 |
+
return out
|
customize/customize_embeddings.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
# Copyright 2021, IBM Corporation.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""
|
19 |
+
Python function to customize json sentences locally.
|
20 |
+
"""
|
21 |
+
|
22 |
+
__author__ = "Vagner Santana, Melina Alberio, Cassia Sanctos and Tiago Machado"
|
23 |
+
__copyright__ = "IBM Corporation 2024"
|
24 |
+
__credits__ = ["Vagner Santana, Melina Alberio, Cassia Sanctos, Tiago Machado"]
|
25 |
+
__license__ = "Apache 2.0"
|
26 |
+
__version__ = "0.0.1"
|
27 |
+
|
28 |
+
import os
|
29 |
+
import json
|
30 |
+
import pandas as pd
|
31 |
+
import numpy as np
|
32 |
+
import customize_helper
|
33 |
+
|
34 |
+
# Sentence transformer model HF
|
35 |
+
model_path = 'models/all-MiniLM-L6-v2'
|
36 |
+
model_id = model_path.split("/")[1]
|
37 |
+
|
38 |
+
# INPUT FILE
|
39 |
+
# Default file with empty embeddings
|
40 |
+
json_in_file = 'prompt-sentences-main/prompt_sentences.json'
|
41 |
+
json_in_file_name = json_in_file.split(".json")[0]
|
42 |
+
|
43 |
+
# OUTPUT FILE
|
44 |
+
json_out_file_name = f'{json_in_file_name}-{model_id}.json'
|
45 |
+
|
46 |
+
prompt_json = json.load(open(json_in_file))
|
47 |
+
prompt_json_embeddings = customize_helper.populate_embeddings(prompt_json, model_path)
|
48 |
+
prompt_json_centroids = customize_helper.populate_centroids(prompt_json_embeddings)
|
49 |
+
customize_helper.save_json(prompt_json_centroids, json_out_file_name)
|
customize/customize_helper.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
# Copyright 2021, IBM Corporation.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""
|
19 |
+
Python helper function to customize json sentences locally.
|
20 |
+
"""
|
21 |
+
|
22 |
+
__author__ = "Vagner Santana, Melina Alberio, Cassia Sanctos and Tiago Machado"
|
23 |
+
__copyright__ = "IBM Corporation 2024"
|
24 |
+
__credits__ = ["Vagner Santana, Melina Alberio, Cassia Sanctos, Tiago Machado"]
|
25 |
+
__license__ = "Apache 2.0"
|
26 |
+
__version__ = "0.0.1"
|
27 |
+
|
28 |
+
import os
|
29 |
+
import json
|
30 |
+
import pandas as pd
|
31 |
+
import numpy as np
|
32 |
+
import math
|
33 |
+
from sentence_transformers import SentenceTransformer
|
34 |
+
|
35 |
+
# Requests embeddings for a given sentence
|
36 |
+
def query_model(texts, model_path):
|
37 |
+
out = []
|
38 |
+
model = SentenceTransformer(model_path)
|
39 |
+
input_embedding = model.encode(texts)
|
40 |
+
out.append(input_embedding)
|
41 |
+
if( out != [] ):
|
42 |
+
return out[0]
|
43 |
+
else:
|
44 |
+
return out
|
45 |
+
|
46 |
+
# Returns euclidean distance between two embeddings
|
47 |
+
def get_distance(embedding1, embedding2):
|
48 |
+
total = 0
|
49 |
+
if( len(embedding1) != len(embedding2)):
|
50 |
+
return math.inf
|
51 |
+
|
52 |
+
for i, obj in enumerate(embedding1):
|
53 |
+
total += math.pow(embedding2[0][i] - embedding1[0][i], 2)
|
54 |
+
return(math.sqrt(total))
|
55 |
+
|
56 |
+
# Returns the centroid for a given value
|
57 |
+
def get_centroid(v, dimension = 384, k = 10):
|
58 |
+
centroid = [0] * dimension
|
59 |
+
count = 0
|
60 |
+
for p in v['prompts']:
|
61 |
+
i = 0
|
62 |
+
while i < len(p['embedding']):
|
63 |
+
centroid[i] += p['embedding'][i]
|
64 |
+
i += 1
|
65 |
+
count += 1
|
66 |
+
i = 0
|
67 |
+
while i < len(centroid):
|
68 |
+
centroid[i] /= count
|
69 |
+
i += 1
|
70 |
+
|
71 |
+
# Update centroid considering only the k-near elements
|
72 |
+
if(len(v['prompts']) <= k):
|
73 |
+
return centroid
|
74 |
+
else:
|
75 |
+
k_items = pd.DataFrame(columns=['embedding', 'distance'])
|
76 |
+
for p in v['prompts']:
|
77 |
+
dist = get_distance(pd.DataFrame(centroid), pd.DataFrame(p['embedding']))
|
78 |
+
k_items = pd.concat([pd.DataFrame([[p['embedding'], dist]], columns=k_items.columns), k_items], ignore_index=True)
|
79 |
+
|
80 |
+
k_items = k_items.sort_values(by='distance')
|
81 |
+
k_items = k_items.head(k)
|
82 |
+
|
83 |
+
# Computing centroid only for the k-near elements
|
84 |
+
centroid = [0] * dimension
|
85 |
+
for i, embedding in enumerate(k_items['embedding']):
|
86 |
+
for j, dimension in enumerate(embedding):
|
87 |
+
centroid[j] += embedding[j]
|
88 |
+
i = 0
|
89 |
+
while i < len(centroid):
|
90 |
+
centroid[i] /= k
|
91 |
+
i += 1
|
92 |
+
return centroid
|
93 |
+
|
94 |
+
def populate_embeddings(prompt_json, model_path):
|
95 |
+
errors, successess = 0, 0
|
96 |
+
for v in prompt_json['positive_values']:
|
97 |
+
for p in v['prompts']:
|
98 |
+
if( p['text'] != '' and p['embedding'] == []): # only considering missing embeddings
|
99 |
+
embedding = query_model(p['text'], model_path)
|
100 |
+
if( 'error' in embedding ):
|
101 |
+
p['embedding'] = []
|
102 |
+
errors += 1
|
103 |
+
else:
|
104 |
+
p['embedding'] = embedding.tolist()
|
105 |
+
#successes += 1
|
106 |
+
|
107 |
+
for v in prompt_json['negative_values']:
|
108 |
+
for p in v['prompts']:
|
109 |
+
if(p['text'] != '' and p['embedding'] == []):
|
110 |
+
embedding = query_model(p['text'], model_path)
|
111 |
+
if('error' in embedding):
|
112 |
+
p['embedding'] = []
|
113 |
+
errors += 1
|
114 |
+
else:
|
115 |
+
p['embedding'] = embedding.tolist()
|
116 |
+
#successes += 1
|
117 |
+
return prompt_json
|
118 |
+
|
119 |
+
def populate_centroids(prompt_json):
|
120 |
+
for v in prompt_json['positive_values']:
|
121 |
+
v['centroid'] = get_centroid(v, dimension = 384, k = 10)
|
122 |
+
for v in prompt_json['negative_values']:
|
123 |
+
v['centroid'] = get_centroid(v, dimension = 384, k = 10)
|
124 |
+
return prompt_json
|
125 |
+
|
126 |
+
# Saving the embeddings for a specific LLM
|
127 |
+
def save_json(prompt_json, json_out_file_name):
|
128 |
+
with open(json_out_file_name, 'w') as outfile:
|
129 |
+
json.dump(prompt_json, outfile)
|
front_log.json
ADDED
File without changes
|
helpers/authenticate_api.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
# Copyright 2021, IBM Corporation.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""
|
19 |
+
Python helper function to authenticate in HF API.
|
20 |
+
"""
|
21 |
+
|
22 |
+
__author__ = "Vagner Santana, Melina Alberio, Cassia Sanctos and Tiago Machado"
|
23 |
+
__copyright__ = "IBM Corporation 2024"
|
24 |
+
__credits__ = ["Vagner Santana, Melina Alberio, Cassia Sanctos, Tiago Machado"]
|
25 |
+
__license__ = "Apache 2.0"
|
26 |
+
__version__ = "0.0.1"
|
27 |
+
|
28 |
+
import os
|
29 |
+
|
30 |
+
def authenticate_api(hf_token, hf_url):
|
31 |
+
"""
|
32 |
+
Function authenticate in HuggingFace API.
|
33 |
+
|
34 |
+
Args:
|
35 |
+
hf_token: HugginFace personal token.
|
36 |
+
hf_url: HuggingFace url to be accessed.
|
37 |
+
|
38 |
+
Returns:
|
39 |
+
An api url and headers.
|
40 |
+
|
41 |
+
Raises:
|
42 |
+
Nothing.
|
43 |
+
"""
|
44 |
+
# Sentence transformer model
|
45 |
+
model_id = "sentence-transformers/all-MiniLM-L6-v2"
|
46 |
+
|
47 |
+
api_url = f"{hf_url}{model_id}"
|
48 |
+
headers = {"Authorization": f"Bearer {hf_token}"}
|
49 |
+
return api_url, headers
|
helpers/get_credentials.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
# Copyright 2021, IBM Corporation.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""
|
19 |
+
Python helper function to get HF credentials.
|
20 |
+
"""
|
21 |
+
|
22 |
+
__author__ = "Vagner Santana, Melina Alberio, Cassia Sanctos and Tiago Machado"
|
23 |
+
__copyright__ = "IBM Corporation 2024"
|
24 |
+
__credits__ = ["Vagner Santana, Melina Alberio, Cassia Sanctos, Tiago Machado"]
|
25 |
+
__license__ = "Apache 2.0"
|
26 |
+
__version__ = "0.0.1"
|
27 |
+
|
28 |
+
import os
|
29 |
+
import sys
|
30 |
+
|
31 |
+
def get_credentials():
|
32 |
+
"""
|
33 |
+
Function that loads HF credentials from env file.
|
34 |
+
The function exits the app if HF token is missing.
|
35 |
+
|
36 |
+
Args:
|
37 |
+
None.
|
38 |
+
|
39 |
+
Returns:
|
40 |
+
hf_token: personal HuggingFace token.
|
41 |
+
hf_url: HuggingFace url to be used.
|
42 |
+
|
43 |
+
Raises:
|
44 |
+
ValueError when hf_token and hf_url
|
45 |
+
values are missing or incorrect.
|
46 |
+
"""
|
47 |
+
# Loading hugging face token from env file
|
48 |
+
default_hf_url = 'https://api-inference.huggingface.co/pipeline/feature-extraction/'
|
49 |
+
try:
|
50 |
+
hf_token = os.environ.get('HF_TOKEN')
|
51 |
+
if not hf_token or hf_token == '<include-token-here>':
|
52 |
+
raise ValueError
|
53 |
+
except:
|
54 |
+
print('Please include your HF_TOKEN in the .env file')
|
55 |
+
sys.exit(1)
|
56 |
+
try:
|
57 |
+
hf_url = os.environ.get('HF_URL')
|
58 |
+
if not hf_url:
|
59 |
+
raise ValueError
|
60 |
+
except:
|
61 |
+
print('Please include your HF_URL in the .env file')
|
62 |
+
return hf_token, default_hf_url
|
63 |
+
return hf_token, hf_url
|
helpers/save_model.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
# Copyright 2021, IBM Corporation.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""
|
19 |
+
Python helper function to save HF model locally.
|
20 |
+
"""
|
21 |
+
|
22 |
+
__author__ = "Vagner Santana, Melina Alberio, Cassia Sanctos and Tiago Machado"
|
23 |
+
__copyright__ = "IBM Corporation 2024"
|
24 |
+
__credits__ = ["Vagner Santana, Melina Alberio, Cassia Sanctos, Tiago Machado"]
|
25 |
+
__license__ = "Apache 2.0"
|
26 |
+
__version__ = "0.0.1"
|
27 |
+
|
28 |
+
import os
|
29 |
+
from sentence_transformers import SentenceTransformer
|
30 |
+
|
31 |
+
def save_model():
|
32 |
+
"""
|
33 |
+
Function that saves an HF model locally.
|
34 |
+
|
35 |
+
Args:
|
36 |
+
None.
|
37 |
+
|
38 |
+
Returns:
|
39 |
+
The model id and local path.
|
40 |
+
|
41 |
+
Raises:
|
42 |
+
Nothing.
|
43 |
+
"""
|
44 |
+
# sentence transformer model
|
45 |
+
model_id = "sentence-transformers/all-MiniLM-L6-v2"
|
46 |
+
|
47 |
+
# download pretrained model
|
48 |
+
model = SentenceTransformer(model_id)
|
49 |
+
model_path = "./models/all-MiniLM-L6-v2/"
|
50 |
+
|
51 |
+
# save to local directory
|
52 |
+
try:
|
53 |
+
model.save(model_path)
|
54 |
+
saved_message = f"model {model_id} saved to {model_path}"
|
55 |
+
print(saved_message)
|
56 |
+
except:
|
57 |
+
('There was an error when saving the model')
|
58 |
+
|
59 |
+
return model_id, model_path
|
60 |
+
|
models/.DS_Store
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cb339d088a1fb5f6b71960caa5f24eaebcafeb1fa0984e463096f11b4a62af0f
|
3 |
+
size 6148
|
models/all-MiniLM-L6-v2/1_Pooling/config.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a19c83805e1ce4174f3fbfec4ac8d3b8dbae0c958f8fd51b80937eb33e0c5335
|
3 |
+
size 296
|
models/all-MiniLM-L6-v2/README.md
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:766a000da416a8a45760fce75dd387cc2ba3a358f7c58b4813a7b222ddb32471
|
3 |
+
size 10659
|
models/all-MiniLM-L6-v2/config.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7ed54a1b81ace26d4a6b348b583d197a0e9b837297dc073748aa327b87d136df
|
3 |
+
size 678
|
models/all-MiniLM-L6-v2/config_sentence_transformers.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3c2b2ccfc43cb4f99b9ea0d7df0a8b60be969b0c5c73fd159a71a82e6d981337
|
3 |
+
size 195
|
models/all-MiniLM-L6-v2/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1377e9af0ca0b016a9f2aa584d6fc71ab3ea6804fae21ef9fb1416e2944057ac
|
3 |
+
size 90864192
|
models/all-MiniLM-L6-v2/modules.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:84e40c8e006c9b1d6c122e02cba9b02458120b5fb0c87b746c41e0207cf642cf
|
3 |
+
size 349
|
models/all-MiniLM-L6-v2/sentence_bert_config.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fc1993fde0a95c24ec6c022539d41cf6e2f7c9721e5415d6fb6897472a9cd4b7
|
3 |
+
size 53
|
models/all-MiniLM-L6-v2/special_tokens_map.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5d5b662e421ea9fac075174bb0688ee0d9431699900b90662acd44b2a350503a
|
3 |
+
size 695
|
models/all-MiniLM-L6-v2/tokenizer.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0
|
3 |
+
size 711661
|
models/all-MiniLM-L6-v2/tokenizer_config.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:085f1ef19e247fdef3c6ff75d5115d7d9c7c3196861380c434af09df3d7cf9bc
|
3 |
+
size 1434
|
models/all-MiniLM-L6-v2/vocab.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3
|
3 |
+
size 231508
|
models/umap/.DS_Store
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:21f3d5183e0e0ae756ae9eca064a916bc04b0dc7cdcb2806f83526a8b1115bd1
|
3 |
+
size 6148
|
models/umap/BAAI/bge-large-en-v1.5/encoder.keras
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cdfcb0b99075067e7269fb788c56511c2aba5d18e756b14e5effb02c30e80797
|
3 |
+
size 1256574
|
models/umap/BAAI/bge-large-en-v1.5/model.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e234d09bc51bd3555472871b04836cddacddea8d75cb912949e6ba93a76002b2
|
3 |
+
size 10386660
|
models/umap/BAAI/bge-large-en-v1.5/parametric_model.keras
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bacff17e3e36455bfbb4a0ba8bc48abf36344d4215f8b3adda2dfdbd85711cc3
|
3 |
+
size 3703730
|
models/umap/intfloat/multilingual-e5-large/encoder.keras
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8881382b6ab4707ff2e8df31cf1603890e6081270512cc77035ae9064d9cddb4
|
3 |
+
size 1256574
|
models/umap/intfloat/multilingual-e5-large/model.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:af512726ece019cbbc184b6bbad01d08e66ab9e214237cf8340bff607195cda0
|
3 |
+
size 10400228
|
models/umap/intfloat/multilingual-e5-large/parametric_model.keras
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:824d79ffe092bfcec6b8a717a09ae675cfc48949220e8fa32e6f5f84f77e587b
|
3 |
+
size 3703730
|
models/umap/sentence-transformers/all-MiniLM-L6-v2/encoder.keras
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:83b438fd70c2a424f7bbd66830407a0bae208422345b2b29f5aac461780b415e
|
3 |
+
size 601210
|
models/umap/sentence-transformers/all-MiniLM-L6-v2/model.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b2423646208b41ec4453455b4b47dd076918cf336d4024f33194ee7052730f2d
|
3 |
+
size 4692948
|
models/umap/sentence-transformers/all-MiniLM-L6-v2/parametric_model.keras
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b55251c23394c30cf259e59cdebb12cb695812eea460d28ec86cbf718c9d8764
|
3 |
+
size 1737648
|
prompt-sentences-main/README.md
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9edf70a963aceb122c9ab26368d6e84b76ad63c3017539aa86740758059d97d9
|
3 |
+
size 2495
|
prompt-sentences-main/prompt_sentences-all-minilm-l6-v2.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bc134e1f98066c06b9377653cca5bcdae111745e3e1b589acd70ddef970a9b94
|
3 |
+
size 19617646
|
prompt-sentences-main/prompt_sentences-bge-large-en-v1.5.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a762a199678eacea340f427dc0e9ad9201326d8a88641f71a943795606562b34
|
3 |
+
size 52222899
|
prompt-sentences-main/prompt_sentences-multilingual-e5-large.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b90342d7dbb6cbe769f63bcb700be768620bba9f92c2ea09996e2d25b2a744ec
|
3 |
+
size 52142750
|
prompt-sentences-main/prompt_sentences.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b88e19f6f529370f58602d291b5b0c32e05536ef4bd9ee102f3cbccba6e8b845
|
3 |
+
size 324504
|
prompt-sentences-main/sentences_by_values-all-minilm-l6-v2.png
ADDED
![]() |
Git LFS Details
|
prompt-sentences-main/sentences_by_values-bge-large-en-v1.5.png
ADDED
![]() |
Git LFS Details
|
prompt-sentences-main/sentences_by_values-multilingual-e5-large.png
ADDED
![]() |
Git LFS Details
|
red-team/README.md
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Red Team Dataset
|
2 |
+
|
3 |
+
## Description
|
4 |
+
|
5 |
+
This red teaming dataset was created to test the limits of the responsible prompting system. Each sentence was written in the style of a potential user's prompt, inspired by the [Awesome ChatGPT prompts dataset](https://github.com/f/awesome-chatgpt-prompts), and contained three parts:
|
6 |
+
|
7 |
+
1. A persona (e.g., “Act as a data scientist with 20 years of experience studying consumer behavior...”),
|
8 |
+
2. A prompt body, which contained 1-2 additional statements specifying a related object and/or additional context/priming (e.g., “Here is a csv file with banking information from 800,00 Americans...”), and
|
9 |
+
3. The user’s inquiry or task (e.g., “Generate a code to classify applicants based on...”).
|
10 |
+
|
11 |
+
## Download
|
12 |
+
|
13 |
+
[Download the red_team.csv file](./red_team.csv).
|
14 |
+
|
15 |
+
## Details and Rationale
|
16 |
+
|
17 |
+
There were 5 different business personas in total, divided so that each persona appeared twice in each task; this was done so as to control for potential differences seen due to the job descriptions in semantic space (and to represent roles that were common in our institutional setting). We were interested in 4 potential issues:
|
18 |
+
|
19 |
+
1. 10 sentences were created to explore embedded or latent ambiguity within values and embeddings and its impact on recommendations. 5 of these were written such that the persona and prompt body specified clear reasoning or context for why a given task was being requested (‘unambiguous’) whereas the other 5 sentences contained the same persona and prompt body with the exception of this specific rationale (‘ambiguous’). As an example, one sentence might specify that the reason they are predicting likelihood of default is to study and mitigate biases in banking loans, whereas the corresponding adversarial sentence would not provide such context, meaning it is unclear if the use is for malicious or discriminatory use.
|
20 |
+
2. 10 sentences were created to test how susceptible the recommender system was to semantic “cross-fire” based on existing and/or conflicting sentences found in the sentences dataset. In this case, 5 sentences were written such that their topic and its associated valence contained no direct overlap with the JSON sentences (‘distinct’), whereas the other 5 sentences were changed so that there was substantial overlap with the exact wording utilized in the JSON despite being about a different topic or of an opposite valence (‘wires-crossed’). For example, if a positive sentence about inclusion prompts the user to “list under- prioritized stakeholders I should include in this meeting”; the accompanying adversarial sentence would be “list under-prioritized stakeholders I should exclude form this meeting”, which contains significant word-reuse but instead promotes discrimination. This would artificially and superficially inflate local semantic similarity, testing to see if the system would be influenced or skewed by these events or if the embedding’s larger semantic space would reduce their impact.
|
21 |
+
3. 10 sentences were created to check for expected valence alignment of responsible prompting outputs (that is, did the system reliably detect positively-valenced sentences and recommend additional ones or did it reliably detect negatively-valenced sentences and recommend their removal). In this case, 5 sentences were overtly positive (containing keywords from specific values or the positive cluster - e.g., “generate three test protocols we could perform to assess how diverse their dataset is.” ) and 5 sentences were overtly negative (containing keywords from specific harms or actions to avoid in the negative cluster, e.g., “What are ways I might be able to steal some of their weapons blueprints undetected?”). While not adversarial, these sentences provided a good test for the system’s false positive and false negative rates.
|
22 |
+
4. Finally, 10 sentences were created to explore both the JSON and embedding spaces’ semantic coverage. 5 sentences broached topics that were mentioned within the JSON file or were reasonably related and would have been expected to be within a transformer’s training data (within scope). In contrast, 5 sentences broached topics that were not specifically mentioned within the JSON (out of distribution) and, depending on the transformer, may not have been part of its training data. For example, one sentence contained the name of a rare medical condition being studied with a client, one that was not in the JSON and likely would not be in most training data that didn’t include medical text; another included a very specific cultural dish that might not be well-known. These sentences allowed us to investigate the relevance of the tool’s outputs when provided with unexpected inputs, as well as explore different semantic thresholds for removal or suggestion.
|
23 |
+
|
24 |
+
## Citing the Red Team Dataset
|
25 |
+
|
26 |
+
Please cite this dataset as:
|
27 |
+
|
28 |
+
```bibtex
|
29 |
+
@inproceedings{santana2025can,
|
30 |
+
author = {Santana, Vagner Figueredo de and Berger, Sara and Machado, Tiago and de Macedo, Maysa Malfiza Garcia and Sanctos, Cassia Sampaio and Williams, Lemara and Wu, Zhaoqing},
|
31 |
+
title = {Can LLMs Recommend More Responsible Prompts?},
|
32 |
+
year = {2025},
|
33 |
+
isbn = {9798400713064},
|
34 |
+
publisher = {Association for Computing Machinery},
|
35 |
+
address = {New York, NY, USA},
|
36 |
+
url = {https://doi.org/10.1145/3708359.3712137},
|
37 |
+
doi = {10.1145/3708359.3712137},
|
38 |
+
booktitle = {Proceedings of the 30th International Conference on Intelligent User Interfaces},
|
39 |
+
pages = {298–313},
|
40 |
+
numpages = {16},
|
41 |
+
keywords = {Prompt Engineering, Responsible Prompting, Responsible AI, Recommender Systems, Recommendation Systems},
|
42 |
+
location = {
|
43 |
+
},
|
44 |
+
series = {IUI '25}
|
45 |
+
}
|
46 |
+
```
|