cetinca commited on
Commit
6784f95
·
verified ·
1 Parent(s): 10d0128

Update package import

Browse files
Files changed (7) hide show
  1. .gitlab-ci.yml +4 -4
  2. app.py +4 -3
  3. modules/nlu.py +11 -14
  4. modules/sentiment.py +0 -8
  5. modules/text2int.py +0 -192
  6. pyproject.toml +40 -0
  7. requirements.txt +4 -12
.gitlab-ci.yml CHANGED
@@ -1,14 +1,14 @@
1
  # Official Python language image.
2
- test_py39:
3
- image: python:3.9
4
  before_script:
5
  - python -v
6
  - pip install -r requirements.txt
7
  script:
8
  - pytest --verbose
9
 
10
- test_py38:
11
- image: python:3.8
12
  before_script:
13
  - python -v
14
  - pip install -r requirements.txt
 
1
  # Official Python language image.
2
+ test_py38:
3
+ image: python:3.8
4
  before_script:
5
  - python -v
6
  - pip install -r requirements.txt
7
  script:
8
  - pytest --verbose
9
 
10
+ test_py39:
11
+ image: python:3.9
12
  before_script:
13
  - python -v
14
  - pip install -r requirements.txt
app.py CHANGED
@@ -8,9 +8,10 @@ from fastapi.staticfiles import StaticFiles
8
  from fastapi.templating import Jinja2Templates
9
  from pydantic import BaseModel
10
 
11
- from modules.nlu import prepare_message_data_for_logging
12
  from mathtext.sentiment import sentiment
13
  from mathtext.text2int import text2int
 
 
14
 
15
  app = FastAPI()
16
 
@@ -47,7 +48,6 @@ def text2int_ep(content: Text = None):
47
  content = {"message": ml_response}
48
  return JSONResponse(content=content)
49
 
50
-
51
  @app.post("/nlu")
52
  async def evaluate_user_message_with_nlu_api(request: Request):
53
  """ Calls NLU APIs on the most recent user message from Turn.io message data and logs the message data
@@ -67,7 +67,7 @@ async def evaluate_user_message_with_nlu_api(request: Request):
67
 
68
  int_api_resp = text2int(message_text)
69
 
70
- if int_api_resp == '32202':
71
  sentiment_api_resp = sentiment(message_text)
72
  # [{'label': 'POSITIVE', 'score': 0.991188645362854}]
73
  sent_data_dict = {'type': 'sentiment', 'data': sentiment_api_resp[0]['label']}
@@ -76,4 +76,5 @@ async def evaluate_user_message_with_nlu_api(request: Request):
76
  prepare_message_data_for_logging(message_data)
77
 
78
  int_data_dict = {'type': 'integer', 'data': int_api_resp}
 
79
  return JSONResponse(content=int_data_dict)
 
8
  from fastapi.templating import Jinja2Templates
9
  from pydantic import BaseModel
10
 
 
11
  from mathtext.sentiment import sentiment
12
  from mathtext.text2int import text2int
13
+ from modules.nlu import prepare_message_data_for_logging
14
+
15
 
16
  app = FastAPI()
17
 
 
48
  content = {"message": ml_response}
49
  return JSONResponse(content=content)
50
 
 
51
  @app.post("/nlu")
52
  async def evaluate_user_message_with_nlu_api(request: Request):
53
  """ Calls NLU APIs on the most recent user message from Turn.io message data and logs the message data
 
67
 
68
  int_api_resp = text2int(message_text)
69
 
70
+ if int_api_resp == 32202:
71
  sentiment_api_resp = sentiment(message_text)
72
  # [{'label': 'POSITIVE', 'score': 0.991188645362854}]
73
  sent_data_dict = {'type': 'sentiment', 'data': sentiment_api_resp[0]['label']}
 
76
  prepare_message_data_for_logging(message_data)
77
 
78
  int_data_dict = {'type': 'integer', 'data': int_api_resp}
79
+
80
  return JSONResponse(content=int_data_dict)
modules/nlu.py CHANGED
@@ -1,18 +1,15 @@
1
- import environ
2
- import json
3
  import os
4
- import requests
5
-
6
  from datetime import datetime
7
- from supabase import create_client
8
 
 
 
9
 
10
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
11
- env = environ.Env()
12
- env_path = os.path.join(BASE_DIR, '.env')
13
- environ.Env.read_env('.env')
14
 
15
- SUPA = create_client(env('SUPABASE_URL'), env('SUPABASE_KEY'))
 
 
 
16
 
17
  def log_message_data_through_supabase_api(table_name, log_data):
18
  return SUPA.table(table_name).insert(log_data).execute()
@@ -28,19 +25,19 @@ def prepare_message_data_for_logging(message_data):
28
  # Autogenerated fields: id, created_at, modified_at
29
  }
30
  project_data_log = log_message_data_through_supabase_api('project', project_data)
31
-
32
  contact_data = {
33
- 'project': project_data_log.data[0]['id'], # FK
34
  'original_contact_id': message_data['message']['_vnd']['v1']['chat']['contact_uuid'],
35
  'urn': "",
36
  'language_code': "en",
37
  'contact_inserted_at': format_datetime_in_isoformat(datetime.now())
38
- # Autogenerated fields: id, created_at, modified_at
39
  }
40
  contact_data_log = log_message_data_through_supabase_api('contact', contact_data)
41
 
42
  message_data = {
43
- 'contact': contact_data_log.data[0]['id'], # FK
44
  'original_message_id': message_data['message']['id'],
45
  'text': message_data['message']['text']['body'],
46
  'direction': message_data['message']['_vnd']['v1']['direction'],
@@ -49,6 +46,6 @@ def prepare_message_data_for_logging(message_data):
49
  'message_inserted_at': message_data['message']['_vnd']['v1']['chat']['inserted_at'],
50
  'message_modified_at': message_data['message']['_vnd']['v1']['chat']['updated_at'],
51
  'message_sent_at': format_datetime_in_isoformat(datetime.now())
52
- # Autogenerated fields: created_at, modified_at
53
  }
54
  message_data_log = log_message_data_through_supabase_api('message', message_data)
 
 
 
1
  import os
 
 
2
  from datetime import datetime
 
3
 
4
+ from dotenv import load_dotenv
5
+ from supabase import create_client
6
 
7
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
 
 
8
 
9
+ load_dotenv()
10
+
11
+ SUPA = create_client(os.environ.get('SUPABASE_URL'), os.environ.get('SUPABASE_KEY'))
12
+
13
 
14
  def log_message_data_through_supabase_api(table_name, log_data):
15
  return SUPA.table(table_name).insert(log_data).execute()
 
25
  # Autogenerated fields: id, created_at, modified_at
26
  }
27
  project_data_log = log_message_data_through_supabase_api('project', project_data)
28
+
29
  contact_data = {
30
+ 'project': project_data_log.data[0]['id'], # FK
31
  'original_contact_id': message_data['message']['_vnd']['v1']['chat']['contact_uuid'],
32
  'urn': "",
33
  'language_code': "en",
34
  'contact_inserted_at': format_datetime_in_isoformat(datetime.now())
35
+ # Autogenerated fields: id, created_at, modified_at
36
  }
37
  contact_data_log = log_message_data_through_supabase_api('contact', contact_data)
38
 
39
  message_data = {
40
+ 'contact': contact_data_log.data[0]['id'], # FK
41
  'original_message_id': message_data['message']['id'],
42
  'text': message_data['message']['text']['body'],
43
  'direction': message_data['message']['_vnd']['v1']['direction'],
 
46
  'message_inserted_at': message_data['message']['_vnd']['v1']['chat']['inserted_at'],
47
  'message_modified_at': message_data['message']['_vnd']['v1']['chat']['updated_at'],
48
  'message_sent_at': format_datetime_in_isoformat(datetime.now())
49
+ # Autogenerated fields: created_at, modified_at
50
  }
51
  message_data_log = log_message_data_through_supabase_api('message', message_data)
modules/sentiment.py DELETED
@@ -1,8 +0,0 @@
1
- from transformers import pipeline
2
-
3
- sentiment_obj = pipeline(task="sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
4
-
5
-
6
- def sentiment(text):
7
- # Returns sentiment value
8
- return sentiment_obj(text)
 
 
 
 
 
 
 
 
 
modules/text2int.py DELETED
@@ -1,192 +0,0 @@
1
- import spacy # noqa
2
-
3
- # import os
4
- # os.environ['KMP_DUPLICATE_LIB_OK']='True'
5
- # import spacy
6
-
7
- # Change this according to what words should be corrected to
8
- SPELL_CORRECT_MIN_CHAR_DIFF = 2
9
-
10
- TOKENS2INT_ERROR_INT = 32202
11
-
12
- ONES = [
13
- "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
14
- "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
15
- "sixteen", "seventeen", "eighteen", "nineteen",
16
- ]
17
-
18
- CHAR_MAPPING = {
19
- "-": " ",
20
- "_": " ",
21
- "and": " ",
22
- }
23
- # CHAR_MAPPING.update((str(i), word) for i, word in enumerate([" " + s + " " for s in ONES]))
24
- TOKEN_MAPPING = {
25
- "and": " ",
26
- "oh": "0",
27
- }
28
-
29
-
30
- def find_char_diff(a, b):
31
- # Finds the character difference between two str objects by counting the occurences of every character. Not edit distance.
32
- char_counts_a = {}
33
- char_counts_b = {}
34
- for char in a:
35
- if char in char_counts_a.keys():
36
- char_counts_a[char] += 1
37
- else:
38
- char_counts_a[char] = 1
39
- for char in b:
40
- if char in char_counts_b.keys():
41
- char_counts_b[char] += 1
42
- else:
43
- char_counts_b[char] = 1
44
- char_diff = 0
45
- for i in char_counts_a:
46
- if i in char_counts_b.keys():
47
- char_diff += abs(char_counts_a[i] - char_counts_b[i])
48
- else:
49
- char_diff += char_counts_a[i]
50
- return char_diff
51
-
52
-
53
- def tokenize(text):
54
- text = text.lower()
55
- # print(text)
56
- text = replace_tokens(''.join(i for i in replace_chars(text)).split())
57
- # print(text)
58
- text = [i for i in text if i != ' ']
59
- # print(text)
60
- output = []
61
- for word in text:
62
- # print(word)
63
- output.append(convert_word_to_int(word))
64
- output = [i for i in output if i != ' ']
65
- # print(output)
66
- return output
67
-
68
-
69
- def detokenize(tokens):
70
- return ' '.join(tokens)
71
-
72
-
73
- def replace_tokens(tokens, token_mapping=TOKEN_MAPPING):
74
- return [token_mapping.get(tok, tok) for tok in tokens]
75
-
76
-
77
- def replace_chars(text, char_mapping=CHAR_MAPPING):
78
- return [char_mapping.get(c, c) for c in text]
79
-
80
-
81
- def convert_word_to_int(in_word, numwords={}):
82
- # Converts a single word/str into a single int
83
- tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
84
- scales = ["hundred", "thousand", "million", "billion", "trillion"]
85
- if not numwords:
86
- for idx, word in enumerate(ONES):
87
- numwords[word] = idx
88
- for idx, word in enumerate(tens):
89
- numwords[word] = idx * 10
90
- for idx, word in enumerate(scales):
91
- numwords[word] = 10 ** (idx * 3 or 2)
92
- if in_word in numwords:
93
- # print(in_word)
94
- # print(numwords[in_word])
95
- return numwords[in_word]
96
- try:
97
- int(in_word)
98
- return int(in_word)
99
- except ValueError:
100
- pass
101
- # Spell correction using find_char_diff
102
- char_diffs = [find_char_diff(in_word, i) for i in ONES + tens + scales]
103
- min_char_diff = min(char_diffs)
104
- if min_char_diff <= SPELL_CORRECT_MIN_CHAR_DIFF:
105
- return char_diffs.index(min_char_diff)
106
-
107
-
108
- def tokens2int(tokens):
109
- # Takes a list of tokens and returns a int representation of them
110
- types = []
111
- for i in tokens:
112
- if i <= 9:
113
- types.append(1)
114
-
115
- elif i <= 90:
116
- types.append(2)
117
-
118
- else:
119
- types.append(3)
120
- # print(tokens)
121
- if len(tokens) <= 3:
122
- current = 0
123
- for i, number in enumerate(tokens):
124
- if i != 0 and types[i] < types[i - 1] and current != tokens[i - 1] and types[i - 1] != 3:
125
- current += tokens[i] + tokens[i - 1]
126
- elif current <= tokens[i] and current != 0:
127
- current *= tokens[i]
128
- elif 3 not in types and 1 not in types:
129
- current = int(''.join(str(i) for i in tokens))
130
- break
131
- elif '111' in ''.join(str(i) for i in types) and 2 not in types and 3 not in types:
132
- current = int(''.join(str(i) for i in tokens))
133
- break
134
- else:
135
- current += number
136
-
137
- elif 3 not in types and 2 not in types:
138
- current = int(''.join(str(i) for i in tokens))
139
-
140
- else:
141
- """
142
- double_list = []
143
- current_double = []
144
- double_type_list = []
145
- for i in tokens:
146
- if len(current_double) < 2:
147
- current_double.append(i)
148
- else:
149
- double_list.append(current_double)
150
- current_double = []
151
- current_double = []
152
- for i in types:
153
- if len(current_double) < 2:
154
- current_double.append(i)
155
- else:
156
- double_type_list.append(current_double)
157
- current_double = []
158
- print(double_type_list)
159
- print(double_list)
160
- current = 0
161
- for i, type_double in enumerate(double_type_list):
162
- if len(type_double) == 1:
163
- current += double_list[i][0]
164
- elif type_double[0] == type_double[1]:
165
- current += int(str(double_list[i][0]) + str(double_list[i][1]))
166
- elif type_double[0] > type_double[1]:
167
- current += sum(double_list[i])
168
- elif type_double[0] < type_double[1]:
169
- current += double_list[i][0] * double_list[i][1]
170
- #print(current)
171
- """
172
- count = 0
173
- current = 0
174
- for i, token in enumerate(tokens):
175
- count += 1
176
- if count == 2:
177
- if types[i - 1] == types[i]:
178
- current += int(str(token) + str(tokens[i - 1]))
179
- elif types[i - 1] > types[i]:
180
- current += tokens[i - 1] + token
181
- else:
182
- current += tokens[i - 1] * token
183
- count = 0
184
- elif i == len(tokens) - 1:
185
- current += token
186
-
187
- return current
188
-
189
-
190
- def text2int(text):
191
- # Wraps all of the functions up into one
192
- return tokens2int(tokenize(text))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pyproject.toml ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "MathText"
3
+ version = "0.0.3"
4
+ authors = [
5
+ "Sebastian Larsen <[email protected]>",
6
+ "Çetin ÇAKIR <[email protected]>",
7
+ "Hobson Lane <[email protected]>",
8
+ ]
9
+ description = "Natural Language Understanding (text processing) for math symbols, digits, and words with a Gradio user interface and REST API."
10
+ readme = "README.md"
11
+ # requires-python = ">=3.7"
12
+ license = "AGPL-3.0-or-later"
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.8",
16
+ "Programming Language :: Python :: 3.9",
17
+ "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
18
+ "Operating System :: OS Independent",
19
+ ]
20
+
21
+ [tool.poetry.dependencies]
22
+ fastapi = "0.74.*"
23
+ requests = "2.27.*"
24
+ sentencepiece = "0.1.*"
25
+ uvicorn = "0.17.*"
26
+ pydantic = "*"
27
+ supabase = "*"
28
+
29
+ [tool.poetry.group.dev.dependencies]
30
+ pytest = "^7.2"
31
+
32
+ [build-system]
33
+ requires = ["poetry-core"]
34
+ build-backend = "poetry.core.masonry.api"
35
+
36
+ # [build-system]
37
+ # requires = ["hatchling"]
38
+ # build-backend = "hatchling.build"
39
+
40
+ # repository = "https://gitlab.com/tangibleai/community/mathtext-fastapi"
requirements.txt CHANGED
@@ -1,16 +1,8 @@
 
1
  fastapi==0.74.*
2
  requests==2.27.*
3
  sentencepiece==0.1.*
4
- torch==1.12.*
5
- transformers==4.24.*
6
- uvicorn[standard]==0.17.*
7
- pydantic
8
- mathtext @ git+https://gitlab.com/tangibleai/community/mathtext@main
9
- spacy==3.4.*
10
- pandas==1.5.*
11
- matplotlib==3.6.*
12
- pytest==7.2.*
13
- httpx==0.23.*
14
-
15
- django-environ
16
  supabase
 
1
+ mathtext @ git+https://gitlab.com/tangibleai/community/mathtext@main
2
  fastapi==0.74.*
3
  requests==2.27.*
4
  sentencepiece==0.1.*
5
+ uvicorn==0.17.*
6
+ pydantic==1.10.*
7
+ python-dotenv==0.21.*
 
 
 
 
 
 
 
 
 
8
  supabase