Spaces:
Runtime error
Runtime error
Merge branch 'dev-package' into 'main'
Browse filesDraft: Dev package
See merge request tangibleai/community/mathtext-fastapi!5
Files changed (11)
- .gitlab-ci.yml+4-4
- app.py+5-4
- data/master_test_text2int.csvDeleted-90
- modules/__init__.py → mathtext_fastapi/__init__.pyRenamed
- data/text2int_results.csv → mathtext_fastapi/data/text2int_results.csvRenamed+3-1
- modules/nlu.py → mathtext_fastapi/nlu.pyRenamed+9-14
- modules/sentiment.pyDeleted-8
- modules/text2int.pyDeleted-192
- pyproject.tomlAdded+43
- requirements.txt+3-12
- tests/test_text2int.py+11-6
1234567891011121314# Official Python language image.test_py39:image: python:3.9before_script:- python -v- pip install -r requirements.txtscript:- pytest --verbosetest_py38:image: python:3.8before_script:- python -v- pip install -r requirements.txt1234567891011121314# Official Python language image.test_py38:image: python:3.8before_script:- python -v- pip install -r requirements.txtscript:- pytest --verbosetest_py39:image: python:3.9before_script:- python -v- pip install -r requirements.txt
5 unmodified lines67891011121314151650 unmodified lines676869707172732 unmodified lines767778795 unmodified linesfrom fastapi.responses import JSONResponsefrom fastapi.staticfiles import StaticFilesfrom fastapi.templating import Jinja2Templatesfrom pydantic import BaseModelfrom modules.nlu import prepare_message_data_for_loggingfrom mathtext.sentiment import sentimentfrom mathtext.text2int import text2intapp = FastAPI()50 unmodified linesint_api_resp = text2int(message_text)if int_api_resp == '32202':sentiment_api_resp = sentiment(message_text)# [{'label': 'POSITIVE', 'score': 0.991188645362854}]sent_data_dict = {'type': 'sentiment', 'data': sentiment_api_resp[0]['label']}2 unmodified linesprepare_message_data_for_logging(message_data)int_data_dict = {'type': 'integer', 'data': int_api_resp}return JSONResponse(content=int_data_dict)5 unmodified lines67891011121314151650 unmodified lines676869707172732 unmodified lines76777879805 unmodified linesfrom fastapi.responses import JSONResponsefrom fastapi.staticfiles import StaticFilesfrom fastapi.templating import Jinja2Templatesfrom mathtext.sentiment import sentimentfrom mathtext.text2int import text2intfrom pydantic import BaseModelfrom mathtext_fastapi.nlu import prepare_message_data_for_loggingapp = FastAPI()50 unmodified linesint_api_resp = text2int(message_text)if int_api_resp == 32202:sentiment_api_resp = sentiment(message_text)# [{'label': 'POSITIVE', 'score': 0.991188645362854}]sent_data_dict = {'type': 'sentiment', 'data': sentiment_api_resp[0]['label']}2 unmodified linesprepare_message_data_for_logging(message_data)int_data_dict = {'type': 'integer', 'data': int_api_resp}return JSONResponse(content=int_data_dict)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990input,outputfourteen,14forteen,14one thousand four hundred ninety two,1492one thousand ninety two,1092Fourteen Hundred Ninety-Two,1492Fourteen Hundred,1400Ninety nine,99fifteen thousand five hundred-sixty,15560three hundred fifty,350one nine eight five,1985nineteen eighty-five,1985oh one,1six oh 1,601sex,6six,6eight oh,80eighty,80ate,8double eight,88eight three seven five three O nine,8375309eight three seven five three oh nine,8375309eight three seven five three zero nine,8375309eight three seven five three oh ni-ee-ine,8375309two eight,28seven oh eleven,7011seven elevens,77seven eleven,711ninety nine oh five,9905seven 0 seven 0 seven 0 seven,7070707123 hundred,1230005 o 5,50515 o 5,150515-o 5,150515 o-5,1505911-thousand,911000twenty-two twenty-two,2222twenty-two twenty-twos,484four eighty four,484four eighties,320four eighties and nine nineties,1130ninety nine hundred and seventy seven,9977seven thousands,70002 hundreds,20099 thousands and one,99001"forty-five thousand, seven hundred and nine",45709eighty eight hundred eighty,8880a hundred hundred,10000a hundred thousand,100000a hundred million,100000000nineteen ninety nine,1999forteen twenty seven,1427seventeen-thousand and seventy two,17072two hundred and nine,209two thousand ten,2010two thousand and ten,2010twelve million,120000008 billion,8000000000twenty ten,2010thirty-two hundred,3200nine,9forty two,421 2 three,123fourtean,14one tousand four hundred ninty two,1492Furteen Hundrd Ninety-Too,1492forrteen,14sevnteen-thosand and seventy two,17072ninety nine hundred ad seventy seven,9977seven thusands,70002 hunreds,20099 tousands and one,99001eighty ate hundred eighty,8880fourteen Hundred,14008 Bilion,8000000000one million three thousand one,1003001four million nine thousand seven,4009007two million five hundred thousand,2500000two tousand ten,2010two thousand teen,2010tvelve milion,12000000tventy ten,2010tirty-twoo hunred,3200sevn thoosands,7000five,5ten,10one two three and ten,12310ONE MILLion three hunded and fiv,1000305"50,500 and six",50506one_million_and_five,1000005123416 unmodified lines21222324252627input,output,text2int,scorefourteen,14,14,Trueforteen,14,14,Trueone thousand four hundred ninety two,1492,1492,True16 unmodified lineseight three seven five three O nine,8375309,8375329,Falseeight three seven five three oh nine,8375309,8375309,Trueeight three seven five three zero nine,8375309,8375309,Trueeight three seven five three oh ni-ee-ine,8375309,837530619,Falsetwo eight,28,16,Falseseven oh eleven,7011,77,Falseseven elevens,77,77,True12345616 unmodified lines23242526272829input,output,text2int,scorenotanumber,32202,32202,Truethis is not a number,32202,32202,Truefourteen,14,14,Trueforteen,14,14,Trueone thousand four hundred ninety two,1492,1492,True16 unmodified lineseight three seven five three O nine,8375309,8375329,Falseeight three seven five three oh nine,8375309,8375309,Trueeight three seven five three zero nine,8375309,8375309,Trueeight three seven five three oh ni-ee-ine,8375309,837530611,Falsetwo eight,28,16,Falseseven oh eleven,7011,77,Falseseven elevens,77,77,True
1234567891011121314151617189 unmodified lines282930313233343536373839404142434445462 unmodified lines495051525354import environimport jsonimport osimport requestsfrom datetime import datetimefrom supabase import create_clientBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))env = environ.Env()env_path = os.path.join(BASE_DIR, '.env')environ.Env.read_env('.env')SUPA = create_client(env('SUPABASE_URL'), env('SUPABASE_KEY'))def log_message_data_through_supabase_api(table_name, log_data):return SUPA.table(table_name).insert(log_data).execute()9 unmodified lines# Autogenerated fields: id, created_at, modified_at}project_data_log = log_message_data_through_supabase_api('project', project_data)contact_data = {'project': project_data_log.data[0]['id'], # FK'original_contact_id': message_data['message']['_vnd']['v1']['chat']['contact_uuid'],'urn': "",'language_code': "en",'contact_inserted_at': format_datetime_in_isoformat(datetime.now())# Autogenerated fields: id, created_at, modified_at}contact_data_log = log_message_data_through_supabase_api('contact', contact_data)message_data = {'contact': contact_data_log.data[0]['id'], # FK'original_message_id': message_data['message']['id'],'text': message_data['message']['text']['body'],'direction': message_data['message']['_vnd']['v1']['direction'],2 unmodified lines'message_inserted_at': message_data['message']['_vnd']['v1']['chat']['inserted_at'],'message_modified_at': message_data['message']['_vnd']['v1']['chat']['updated_at'],'message_sent_at': format_datetime_in_isoformat(datetime.now())# Autogenerated fields: created_at, modified_at}message_data_log = log_message_data_through_supabase_api('message', message_data)123456789101112139 unmodified lines232425262728293031323334353637383940412 unmodified lines444546474849import osfrom datetime import datetimefrom dotenv import load_dotenvfrom supabase import create_clientload_dotenv()SUPA = create_client(os.environ.get('SUPABASE_URL'), os.environ.get('SUPABASE_KEY'))def log_message_data_through_supabase_api(table_name, log_data):return SUPA.table(table_name).insert(log_data).execute()9 unmodified lines# Autogenerated fields: id, created_at, modified_at}project_data_log = log_message_data_through_supabase_api('project', project_data)contact_data = {'project': project_data_log.data[0]['id'], # FK'original_contact_id': message_data['message']['_vnd']['v1']['chat']['contact_uuid'],'urn': "",'language_code': "en",'contact_inserted_at': format_datetime_in_isoformat(datetime.now())# Autogenerated fields: id, created_at, modified_at}contact_data_log = log_message_data_through_supabase_api('contact', contact_data)message_data = {'contact': contact_data_log.data[0]['id'], # FK'original_message_id': message_data['message']['id'],'text': message_data['message']['text']['body'],'direction': message_data['message']['_vnd']['v1']['direction'],2 unmodified lines'message_inserted_at': message_data['message']['_vnd']['v1']['chat']['inserted_at'],'message_modified_at': message_data['message']['_vnd']['v1']['chat']['updated_at'],'message_sent_at': format_datetime_in_isoformat(datetime.now())# Autogenerated fields: created_at, modified_at}message_data_log = log_message_data_through_supabase_api('message', message_data)
12345678from transformers import pipeline
sentiment_obj = pipeline(task="sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
def sentiment(text): # Returns sentiment value return sentiment_obj(text)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192import spacy # noqa
# import os# os.environ['KMP_DUPLICATE_LIB_OK']='True'# import spacy
# Change this according to what words should be corrected toSPELL_CORRECT_MIN_CHAR_DIFF = 2
TOKENS2INT_ERROR_INT = 32202
ONES = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen",]
CHAR_MAPPING = { "-": " ", "_": " ", "and": " ",}# CHAR_MAPPING.update((str(i), word) for i, word in enumerate([" " + s + " " for s in ONES]))TOKEN_MAPPING = { "and": " ", "oh": "0",}
def find_char_diff(a, b): # Finds the character difference between two str objects by counting the occurences of every character. Not edit distance. char_counts_a = {} char_counts_b = {} for char in a: if char in char_counts_a.keys(): char_counts_a[char] += 1 else: char_counts_a[char] = 1 for char in b: if char in char_counts_b.keys(): char_counts_b[char] += 1 else: char_counts_b[char] = 1 char_diff = 0 for i in char_counts_a: if i in char_counts_b.keys(): char_diff += abs(char_counts_a[i] - char_counts_b[i]) else: char_diff += char_counts_a[i] return char_diff
def tokenize(text): text = text.lower() # print(text) text = replace_tokens(''.join(i for i in replace_chars(text)).split()) # print(text) text = [i for i in text if i != ' '] # print(text) output = [] for word in text: # print(word) output.append(convert_word_to_int(word)) output = [i for i in output if i != ' '] # print(output) return output
def detokenize(tokens): return ' '.join(tokens)
def replace_tokens(tokens, token_mapping=TOKEN_MAPPING): return [token_mapping.get(tok, tok) for tok in tokens]
def replace_chars(text, char_mapping=CHAR_MAPPING): return [char_mapping.get(c, c) for c in text]
def convert_word_to_int(in_word, numwords={}): # Converts a single word/str into a single int tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] scales = ["hundred", "thousand", "million", "billion", "trillion"] if not numwords: for idx, word in enumerate(ONES): numwords[word] = idx for idx, word in enumerate(tens): numwords[word] = idx * 10 for idx, word in enumerate(scales): numwords[word] = 10 ** (idx * 3 or 2) if in_word in numwords: # print(in_word) # print(numwords[in_word]) return numwords[in_word] try: int(in_word) return int(in_word) except ValueError: pass # Spell correction using find_char_diff char_diffs = [find_char_diff(in_word, i) for i in ONES + tens + scales] min_char_diff = min(char_diffs) if min_char_diff <= SPELL_CORRECT_MIN_CHAR_DIFF: return char_diffs.index(min_char_diff)
def tokens2int(tokens): # Takes a list of tokens and returns a int representation of them types = [] for i in tokens: if i <= 9: types.append(1)
elif i <= 90: types.append(2)
else: types.append(3) # print(tokens) if len(tokens) <= 3: current = 0 for i, number in enumerate(tokens): if i != 0 and types[i] < types[i - 1] and current != tokens[i - 1] and types[i - 1] != 3: current += tokens[i] + tokens[i - 1] elif current <= tokens[i] and current != 0: current *= tokens[i] elif 3 not in types and 1 not in types: current = int(''.join(str(i) for i in tokens)) break elif '111' in ''.join(str(i) for i in types) and 2 not in types and 3 not in types: current = int(''.join(str(i) for i in tokens)) break else: current += number
elif 3 not in types and 2 not in types: current = int(''.join(str(i) for i in tokens))
else: """ double_list = [] current_double = [] double_type_list = [] for i in tokens: if len(current_double) < 2: current_double.append(i) else: double_list.append(current_double) current_double = [] current_double = [] for i in types: if len(current_double) < 2: current_double.append(i) else: double_type_list.append(current_double) current_double = [] print(double_type_list) print(double_list) current = 0 for i, type_double in enumerate(double_type_list): if len(type_double) == 1: current += double_list[i][0] elif type_double[0] == type_double[1]: current += int(str(double_list[i][0]) + str(double_list[i][1])) elif type_double[0] > type_double[1]: current += sum(double_list[i]) elif type_double[0] < type_double[1]: current += double_list[i][0] * double_list[i][1] #print(current) """ count = 0 current = 0 for i, token in enumerate(tokens): count += 1 if count == 2: if types[i - 1] == types[i]: current += int(str(token) + str(tokens[i - 1])) elif types[i - 1] > types[i]: current += tokens[i - 1] + token else: current += tokens[i - 1] * token count = 0 elif i == len(tokens) - 1: current += token
return current
def text2int(text): # Wraps all of the functions up into one return tokens2int(tokenize(text))12345678910111213141516171819202122232425262728293031323334353637383940414243[tool.poetry]name = "MathText_FastAPI"version = "0.0.1"authors = [ "Sebastian Larsen <sebastianlarson22@gmail.com>", "Çetin ÇAKIR <cetincakirtr@gmail.com>", "Hobson Lane <gitlab@totalgood.com>", ]description = "Natural Language Understanding (text processing) for math symbols, digits, and words with a Gradio user interface and REST API."readme = "README.md"# requires-python = ">=3.8"license = "AGPL-3.0-or-later"classifiers = [ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)", "Operating System :: OS Independent",]
[tool.poetry.dependencies]mathtext = {git = "https://gitlab.com/tangibleai/community/mathtext", rev = "main"}fastapi = "0.74.*"pydantic = "*"python = "^3.8,<3.10"requests = "2.27.*"sentencepiece = "0.1.*"supabase = "*"uvicorn = "0.17.*"
[tool.poetry.group.dev.dependencies]pytest = "^7.2"
[build-system]requires = ["poetry-core"]build-backend = "poetry.core.masonry.api"
# [build-system]# requires = ["hatchling"]# build-backend = "hatchling.build"
# repository = "https://gitlab.com/tangibleai/community/mathtext-fastapi"12345678910111213141516fastapi==0.74.*requests==2.27.*sentencepiece==0.1.*torch==1.12.*transformers==4.24.*uvicorn[standard]==0.17.*pydanticmathtext @ git+https://gitlab.com/tangibleai/community/mathtext@mainspacy==3.4.*pandas==1.5.*matplotlib==3.6.*pytest==7.2.*httpx==0.23.*django-environsupabase1234567mathtext @ git+https://gitlab.com/tangibleai/community/mathtext@mainfastapi==0.74.*pydantic==1.10.*requests==2.27.*sentencepiece==0.1.*supabaseuvicorn==0.17.*
12345678910113 unmodified lines15161718192014 unmodified lines353637383940414243444546474849import unittestimport pandas as pdfrom fastapi.testclient import TestClientfrom app import appTEST_DATA_FILE = "data/master_test_text2int.csv"client = TestClient(app)3 unmodified linesdef setUp(self):"""Creates a fastapi test client"""self.client = TestClient(app)def get_response_text2int(self, text):"""Makes a post request to the endpoint"""14 unmodified linesdef test_acc_score_text2int(self):"""Calculates accuracy score for endpoint"""df = pd.read_csv(TEST_DATA_FILE)df["text2int"] = df["input"].apply(func=self.get_response_text2int)df["score"] = df[["output", "text2int"]].apply(lambda row: row[0] == row[1],axis=1)df.to_csv("data/text2int_results.csv", index=False)acc_score = df["score"].mean().__round__(2)self.assertGreaterEqual(acc_score, 0.5, f"Accuracy score: '{acc_score}'. Value is too low!")123456789101112131415163 unmodified lines2021222324252614 unmodified lines4142434445464748495051525354import unittestfrom pathlib import Pathimport pandas as pdfrom fastapi.testclient import TestClientfrom app import app# The raw file URL has to be used for GitLab.URL = "https://gitlab.com/tangibleai/community/mathtext/-/raw/main/mathtext/data/master_test_text2int.csv"DATA_DIR = Path(__file__).parent.parent / "mathtext_fastapi" / "data"print(DATA_DIR)client = TestClient(app)3 unmodified linesdef setUp(self):"""Creates a fastapi test client"""self.client = TestClient(app)self.df = pd.read_csv(URL)def get_response_text2int(self, text):"""Makes a post request to the endpoint"""14 unmodified linesdef test_acc_score_text2int(self):"""Calculates accuracy score for endpoint"""self.df["text2int"] = self.df["input"].apply(func=self.get_response_text2int)self.df["score"] = self.df[["output", "text2int"]].apply(lambda row: row[0] == row[1],axis=1)self.df.to_csv(f"{DATA_DIR}/text2int_results.csv", index=False)acc_score = self.df["score"].mean().__round__(2)self.assertGreaterEqual(acc_score, 0.5, f"Accuracy score: '{acc_score}'. Value is too low!")
.gitlab-ci.yml+4-4
app.py+5-4
data/master_test_text2int.csvDeleted-90
modules/__init__.py → mathtext_fastapi/__init__.pyRenamed
data/text2int_results.csv → mathtext_fastapi/data/text2int_results.csvRenamed+3-1
modules/nlu.py → mathtext_fastapi/nlu.pyRenamed+9-14
modules/sentiment.pyDeleted-8
modules/text2int.pyDeleted-192
pyproject.tomlAdded+43
requirements.txt+3-12
tests/test_text2int.py+11-6