liujch1998 commited on
Commit
c942159
β€’
1 Parent(s): 619f8f8

Chrome extension

Browse files
app.py CHANGED
@@ -311,9 +311,9 @@ with gr.Blocks() as demo:
311
 
312
  We'd love your feedback! Please indicate whether you agree or disagree with Vera's prediction (and don't mind the percentage numbers). If you're unsure or the statement doesn't have a certain correctness label, please select "Uncertain". If your input is actually not a statement about commonsense, please select "I don't think this is a statement about commonsense".
313
 
314
- :warning: **Intended Use**: Vera is a research prototype and may make mistakes. Do not use for making critical decisions. It is intended to predict the correctness of commonsense statements, and may be unreliable when taking input out of this scope. **DO NOT input encyclopedic facts.** Vera is trained on **English** data only, please do not input statements in other languages.
315
 
316
- :warning: **Data Collection**: By default, we are collecting the inputs entered in this app to further improve and evaluate the model. Do not share any personal or sensitive information while using the app! You can opt out of this data collection by removing the checkbox below:
317
  '''
318
  )
319
  with gr.Row():
 
311
 
312
  We'd love your feedback! Please indicate whether you agree or disagree with Vera's prediction (and don't mind the percentage numbers). If you're unsure or the statement doesn't have a certain correctness label, please select "Uncertain". If your input is actually not a statement about commonsense, please select "I don't think this is a statement about commonsense".
313
 
314
+ **Intended Use**: Vera is a research prototype and may make mistakes. Do not use for making critical decisions. It is intended to predict the correctness of commonsense statements, and may be unreliable when taking input out of this scope. **DO NOT input encyclopedic facts.** Vera is trained on **English** data only, please do not input statements in other languages.
315
 
316
+ **Data Collection**: By default, we are collecting the inputs entered in this app to further improve and evaluate the model. Do not share any personal or sensitive information while using the app! You can opt out of this data collection by removing the checkbox below:
317
  '''
318
  )
319
  with gr.Row():
backend/README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Vera backend
2
+
3
+ [http://qa.cs.washington.edu:8372/](http://qa.cs.washington.edu:8372/)
4
+
5
+ This demo runs on port 8372, so make sure this port is whitelisted in UFW:
6
+ ```
7
+ sudo ufw allow 8372
8
+ sudo ufw status
9
+ ```
10
+ Also, make sure port 80 and 443 are whitelisted.
11
+
12
+ This demo requires HTTPS, so make sure HTTPS is enabled on this server.
13
+ This is what I did:
14
+ 1. Follwing <https://blog.miguelgrinberg.com/post/running-your-flask-application-over-https>
15
+ 1. Make sure nginx is running: `sudo service nginx status`
16
+ 1. Add the following lines to `/etc/nginx/nginx.conf`
17
+ ```
18
+ server {
19
+ listen 80;
20
+ server_name qa.cs.washington.edu;
21
+ location ~ /.well-known {
22
+ root /home/gary/cd-pi-demo/backend;
23
+ }
24
+ location / {
25
+ return 301 https://$host$request_uri;
26
+ }
27
+ }
28
+ ```
29
+ 1. Use certbot to create a certificate: `sudo certbot certonly --webroot -w /home/gary/cd-pi-demo/backend/ -d qa.cs.washington.edu`
30
+ 1. Add the following lines to `/etc/nginx/nginx.conf`
31
+ ```
32
+ server {
33
+ listen 443 ssl http2;
34
+ server_name qa.cs.washington.edu;
35
+ ssl_certificate /etc/letsencrypt/live/qa.cs.washington.edu/fullchain.pem;
36
+ ssl_certificate_key /etc/letsencrypt/live/qa.cs.washington.edu/privkey.pem;
37
+ # ...
38
+ }
39
+ ```
40
+
41
+ Then, run the following command to spin up the demo:
42
+ ```
43
+ CUDA_VISIBLE_DEVICES=1 sudo ~/anaconda3/envs/default/bin/python run.py
44
+ ```
45
+
46
+ To test the demo, run this command in bash:
47
+ ```
48
+ curl https://qa.cs.washington.edu:8372 -X POST -d '{"statement": "Hello."}' -H "content-type: application/json"
49
+ ```
backend/run.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, redirect, request, jsonify, make_response
2
+ import datetime
3
+
4
+ import torch
5
+ import transformers
6
+
7
+ device = torch.device('cuda')
8
+
9
+ MODEL_NAME = 'liujch1998/vera'
10
+
11
+ class Interactive:
12
+ def __init__(self):
13
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(MODEL_NAME)
14
+ self.model = transformers.T5EncoderModel.from_pretrained(MODEL_NAME, low_cpu_mem_usage=True, device_map='auto', torch_dtype='auto', offload_folder='offload')
15
+ self.model.D = self.model.shared.embedding_dim
16
+ self.linear = torch.nn.Linear(self.model.D, 1, dtype=self.model.dtype).to(device)
17
+ self.linear.weight = torch.nn.Parameter(self.model.shared.weight[32099, :].unsqueeze(0)) # (1, D)
18
+ self.linear.bias = torch.nn.Parameter(self.model.shared.weight[32098, 0].unsqueeze(0)) # (1)
19
+ self.model.eval()
20
+ self.t = self.model.shared.weight[32097, 0].item()
21
+
22
+ def run(self, statement):
23
+ input_ids = self.tokenizer.batch_encode_plus([statement], return_tensors='pt', padding='longest', truncation='longest_first', max_length=128).input_ids.to(device)
24
+ with torch.no_grad():
25
+ output = self.model(input_ids)
26
+ last_hidden_state = output.last_hidden_state.to(device) # (B=1, L, D)
27
+ hidden = last_hidden_state[0, -1, :] # (D)
28
+ logit = self.linear(hidden).squeeze(-1) # ()
29
+ logit_calibrated = logit / self.t
30
+ score = logit.sigmoid()
31
+ score_calibrated = logit_calibrated.sigmoid()
32
+ return {
33
+ 'timestamp': datetime.datetime.now().strftime('%Y%m%d-%H%M%S'),
34
+ 'statement': statement,
35
+ 'logit': logit.item(),
36
+ 'logit_calibrated': logit_calibrated.item(),
37
+ 'score': score.item(),
38
+ 'score_calibrated': score_calibrated.item(),
39
+ }
40
+
41
+ interactive = Interactive()
42
+ app = Flask(__name__)
43
+
44
+ @app.route('/', methods=['GET', 'POST'])
45
+ def main():
46
+ try:
47
+ print(request)
48
+ data = request.get_json()
49
+ statement = data.get('statement')
50
+ except Exception as e:
51
+ return jsonify({
52
+ 'success': False,
53
+ 'message': 'Please provide a statement.',
54
+ }), 400
55
+ try:
56
+ result = interactive.run(statement)
57
+ except Exception as e:
58
+ return jsonify({
59
+ 'success': False,
60
+ 'message': 'Internal error.',
61
+ }), 500
62
+ return jsonify(result)
63
+
64
+ if __name__ == "__main__":
65
+ app.run(host="0.0.0.0", port=8372, threaded=True, ssl_context=('/etc/letsencrypt/live/qa.cs.washington.edu/fullchain.pem', '/etc/letsencrypt/live/qa.cs.washington.edu/privkey.pem'))
66
+ # 8372 is when you type Vera on a phone keypad
chrome-ext/README.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Vera Chrome Extension
2
+
3
+ This is a Chrome extension that verifies commonsense statements in-the-wild, using Vera.
4
+
5
+ To install, go to `chrome://extensions`, enable developer mode, and click "Load unpacked extension". Select the `chrome-extension` directory in this repository.
6
+
7
+ Make sure that the backend is running on `https://qa.cs.washington.edu:8372` before using the extension.
chrome-ext/background.js ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ chrome.action.onClicked.addListener((tab) => {
2
+ chrome.scripting.executeScript({
3
+ target: { tabId: tab.id },
4
+ func: getHighlightedText,
5
+ }, (result) => {
6
+ if (chrome.runtime.lastError) {
7
+ console.error(chrome.runtime.lastError.message);
8
+ return;
9
+ }
10
+ if (result.length == 0) {
11
+ console.error('No result returned by getHighlightedText!');
12
+ return;
13
+ }
14
+ let text = result[0].result;
15
+ if (text.length > 0) {
16
+ getPlausibility(text, tab);
17
+ }
18
+ });
19
+ })
20
+
21
+ // this function is executed in the context of the current tab
22
+ function getHighlightedText() {
23
+ let text = window.getSelection().toString();
24
+ console.log(`Highlighted text: ${text}`);
25
+ if (text.length == 0) {
26
+ alert('Please highlight some text first!');
27
+ }
28
+ return text;
29
+ }
30
+
31
+ // this function is executed in the context of the extension background
32
+ function getPlausibility(text, tab) {
33
+ const URL = 'https://qa.cs.washington.edu:8372';
34
+ const data = { statement: text };
35
+ fetch(URL, {
36
+ method: 'POST',
37
+ headers: {
38
+ 'Content-Type': 'application/json',
39
+ },
40
+ body: JSON.stringify(data),
41
+ })
42
+ .then(response => response.json())
43
+ .then(output => {
44
+ chrome.scripting.executeScript({
45
+ target: { tabId: tab.id },
46
+ func: (statement, score) => {
47
+ disp_score = Math.round(score * 100);
48
+ alert(`Statement: ${statement}\nPlausibility: ${disp_score}%`);
49
+ },
50
+ args: [output.statement, output.score_calibrated],
51
+ });
52
+ })
53
+ .catch((error) => console.error('Error:', error));
54
+ }
chrome-ext/images/aloe-128.png ADDED
chrome-ext/images/aloe-16.png ADDED
chrome-ext/images/aloe-32.png ADDED
chrome-ext/images/aloe-48.png ADDED
chrome-ext/manifest.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "manifest_version": 3,
3
+ "name": "Vera",
4
+ "description": "Verify commonsense statements in-the-wild.",
5
+ "version": "1.0",
6
+ "icons": {
7
+ "16": "images/aloe-16.png",
8
+ "32": "images/aloe-32.png",
9
+ "48": "images/aloe-48.png",
10
+ "128": "images/aloe-128.png"
11
+ },
12
+ "background": {
13
+ "service_worker": "background.js"
14
+ },
15
+ "action": {
16
+ "default_icon": {
17
+ "16": "images/aloe-16.png",
18
+ "32": "images/aloe-32.png",
19
+ "48": "images/aloe-48.png",
20
+ "128": "images/aloe-128.png"
21
+ }
22
+ },
23
+ "permissions": ["scripting", "activeTab"],
24
+ "host_permissions": [
25
+ "https://qa.cs.washington.edu/"
26
+ ],
27
+ "commands": {
28
+ "_execute_action": {
29
+ "suggested_key": {
30
+ "default": "Ctrl+B",
31
+ "mac": "Command+B"
32
+ }
33
+ }
34
+ }
35
+ }