Upload 3 files
Browse files- Dockerfile +20 -0
- app.py +129 -0
- requirements.txt +6 -0
Dockerfile
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.9
|
2 |
+
|
3 |
+
WORKDIR /code
|
4 |
+
|
5 |
+
COPY ./requirements.txt /code/requirements.txt
|
6 |
+
|
7 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
8 |
+
|
9 |
+
RUN useradd -m -u 1000 user
|
10 |
+
|
11 |
+
USER user
|
12 |
+
|
13 |
+
ENV HOME=/home/user \
|
14 |
+
PATH=/home/user/.local/bin:$PATH
|
15 |
+
|
16 |
+
WORKDIR $HOME/app
|
17 |
+
|
18 |
+
COPY --chown=user . $HOME/app
|
19 |
+
|
20 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, Query
|
2 |
+
import torch
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from transformers import AutoTokenizer, AutoModel
|
5 |
+
import re
|
6 |
+
from fastapi import FastAPI, Depends
|
7 |
+
from fastapi_health import health
|
8 |
+
import logging
|
9 |
+
import sys
|
10 |
+
logger = logging.getLogger(__name__)
|
11 |
+
|
12 |
+
logging.basicConfig(
|
13 |
+
level=logging.getLevelName("INFO"),
|
14 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
15 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
16 |
+
logging.info('Logging module started')
|
17 |
+
|
18 |
+
def get_session():
|
19 |
+
return True
|
20 |
+
|
21 |
+
def is_database_online(session: bool = Depends(get_session)):
|
22 |
+
return session
|
23 |
+
|
24 |
+
app = FastAPI()
|
25 |
+
app.add_api_route("/healthz", health([is_database_online]))
|
26 |
+
|
27 |
+
|
28 |
+
class EmbeddingModels:
|
29 |
+
def __init__(self):
|
30 |
+
device="cuda" if torch.cuda.is_available() else "cpu"
|
31 |
+
self.device = device
|
32 |
+
# print(f"Using device {self.device}")
|
33 |
+
self.text_model_ID = 'Alibaba-NLP/gte-large-en-v1.5'
|
34 |
+
self.text_model, self.text_tokenizer = self.get_text_model_info(self.text_model_ID)
|
35 |
+
|
36 |
+
|
37 |
+
def get_text_model_info(self, model_ID):
|
38 |
+
if self.device == 'cuda':
|
39 |
+
logging.info('Using Device CUDA')
|
40 |
+
tokenizer = AutoTokenizer.from_pretrained(model_ID)
|
41 |
+
model = AutoModel.from_pretrained(
|
42 |
+
model_ID,
|
43 |
+
trust_remote_code=True,
|
44 |
+
unpad_inputs=True,
|
45 |
+
use_memory_efficient_attention=True,
|
46 |
+
).to(self.device)
|
47 |
+
logging.info('xfomrer based memory_efficient_attention enabled as device is cuda')
|
48 |
+
else:
|
49 |
+
logging.info('Using Device CPU')
|
50 |
+
tokenizer = AutoTokenizer.from_pretrained(model_ID)
|
51 |
+
model = AutoModel.from_pretrained(
|
52 |
+
model_ID,
|
53 |
+
trust_remote_code=True,
|
54 |
+
).to(self.device)
|
55 |
+
logging.info(' memory_efficient_attention is not supported as device is cpu')
|
56 |
+
|
57 |
+
return model, tokenizer
|
58 |
+
|
59 |
+
|
60 |
+
def preprocessing_patent_data(self,text):
|
61 |
+
# Removing Common tags in patent
|
62 |
+
pattern0 = r'\b(SUBSTITUTE SHEET RULE 2 SUMMARY OF THE INVENTION|BRIEF DESCRIPTION OF PREFERRED EMBODIMENTS|BRIEF DESCRIPTION OF THE DRAWINGS/FIGURES|BEST MODE FOR CARRYING OUT THE INVENTION|BACKGROUND AND SUMMARY OF THE INVENTION|FIELD AND BACKGROUND OF THE INVENTION|BACKGROUND OF THE PRESENT INVENTION|FIELD AND BACKGROUND OF INVENTION|STAND DER TECHNIK- BACKGROUND ART|BRIEF DESCRIPTION OF THE DRAWINGS|DESCRIPTION OF THE RELATED ART|BRIEF SUMMARY OF THE INVENTION|UTILITY MODEL CLAIMS A CONTENT|DESCRIPTION OF BACKGROUND ART|BRIEF DESCRIPTION OF DRAWINGS|BACKGROUND OF THE INVENTION|BACKGROUND TO THE INVENTION|TÉCNICA ANTERIOR- PRIOR ART|DISCLOSURE OF THE INVENTION|BRIEF SUMMARY OF INVENTION|BACKGROUND OF RELATED ART|SUMMARY OF THE DISCLOSURE|SUMMARY OF THE INVENTIONS|SUMMARY OF THE INVENTION|OBJECTS OF THE INVENTION|THE CONTENT OF INVENTION|DISCLOSURE OF INVENTION|Disclosure of Invention|Complete Specification|RELATED BACKGROUND ART|BACKGROUND INFORMATION|BACKGROUND TECHNOLOGY|DETAILED DESCRIPTION|SUMMARY OF INVENTION|DETAILED DESCRIPTION|PROBLEM TO BE SOLVED|EFFECT OF INVENTION|WHAT IS CLAIMED IS|What is claimed is|What is Claim is|SUBSTITUTE SHEET|SELECTED DRAWING|BACK GROUND ART|BACKGROUND ART|Background Art|JPO&INPIT|CONSTITUTION|DEFINITIONS|Related Art|BACKGROUND|JPO&INPIT|JPO&NCIPI|COPYRIGHT|SOLUTION|SUMMARY)\b'
|
63 |
+
text = re.sub(pattern0, '[SEP]', text, flags=re.IGNORECASE)
|
64 |
+
text = ' '.join(text.split())
|
65 |
+
# Removing all tags between Heading to /Heading and id=
|
66 |
+
regex = r'<\s*heading[^>]*>(.*?)<\s*/\s*heading>|<[^<]+>|id=\"p-\d+\"|:'
|
67 |
+
result = re.sub(regex, '[SEP]', text, flags=re.IGNORECASE)
|
68 |
+
# find_formula_names from pat text to exclude it from below logic regex
|
69 |
+
chemical_list = []
|
70 |
+
pattern1 = r'\b((?:(?:H|He|Li|Be|B|C|N|O|F|Ne|Na|Mg|Al|Si|P|S|Cl|Ar|K|Ca|Sc|Ti|V|Cr|Mn|Fe|Co|Ni|Cu|Zn|Ga|Ge|As|Se|Br|Kr|Rb|Sr|Y|Zr|Nb|Mo|Tc|Ru|Rh|Pd|Ag|Cd|In|Sn|Sb|Te|I|Xe|Cs|Ba|La|Hf|Ta|W|Re|Os|Ir|Pt|Au|Hg|Tl|Pb|Bi|Po|At|Rn|Fr|Ra|Ac|Rf|Db|Sg|Bh|Hs|Mt|Ds|Rg|Cn|Nh|Fl|Mc|Lv|Ts|Og|Ce|Pr|Nd|Pm|Sm|Eu|Gd|Tb|Dy|Ho|Er|Tm|Yb|Lu|Th|Pa|U|Np|Pu|Am|Cm|Bk|Cf|Es|Fm|Md|No|Lr)\d*)+)\b'
|
71 |
+
|
72 |
+
formula_names = re.findall(pattern1, result)
|
73 |
+
for formula in formula_names:
|
74 |
+
if len(formula)>=2:
|
75 |
+
chemical_list.append(formula)
|
76 |
+
# print("chemical_list:", chemical_list)
|
77 |
+
|
78 |
+
# Remove numbers and alphanum inside brackets excluding chemical forms
|
79 |
+
pattern2 = r"\((?![A-Za-z]+\))[\w\d\s,-]+\)|\([A-Za-z]\)"
|
80 |
+
def keep_strings(text):
|
81 |
+
matched = text.group(0)
|
82 |
+
if any(item in matched for item in chemical_list):
|
83 |
+
return matched
|
84 |
+
return ' '
|
85 |
+
cleaned_text = re.sub(pattern2, keep_strings, result)
|
86 |
+
cleaned_text = ' '.join(cleaned_text.split())
|
87 |
+
cleaned_text= re.sub("(\[SEP\]+\s*)+", ' ', cleaned_text, flags=re.IGNORECASE)
|
88 |
+
# below new logic to remove chemical compounds (eg.chemical- polymerizable compounds)
|
89 |
+
p_text2=re.sub('[\—\-\═\=]', ' ', cleaned_text)
|
90 |
+
pattern1 = r'\b((?:(?:H|He|Li|Be|B|C|N|O|F|Ne|Na|Mg|Al|Si|P|S|Cl|Ar|K|Ca|Sc|Ti|V|Cr|Mn|Fe|Co|Ni|Cu|Zn|Ga|Ge|As|Se|Br|Kr|Rb|Sr|Y|Zr|Nb|Mo|Tc|Ru|Rh|Pd|Ag|Cd|In|Sn|Sb|Te|I|Xe|Cs|Ba|La|Hf|Ta|W|Re|Os|Ir|Pt|Au|Hg|Tl|Pb|Bi|Po|At|Rn|Fr|Ra|Ac|Rf|Db|Sg|Bh|Hs|Mt|Ds|Rg|Cn|Nh|Fl|Mc|Lv|Ts|Og|Ce|Pr|Nd|Pm|Sm|Eu|Gd|Tb|Dy|Ho|Er|Tm|Yb|Lu|Th|Pa|U|Np|Pu|Am|Cm|Bk|Cf|Es|Fm|Md|No|Lr)\d*)+)\b'
|
91 |
+
cleaned_text = re.sub(pattern1, "", p_text2)
|
92 |
+
cleaned_text = re.sub(' ,+|, +', ' ', cleaned_text)
|
93 |
+
cleaned_text = re.sub(' +', ' ', cleaned_text)
|
94 |
+
cleaned_text = re.sub('\.+', '.', cleaned_text)
|
95 |
+
cleaned_text = re.sub('[0-9] [0-9] +', ' ', cleaned_text)
|
96 |
+
cleaned_text = re.sub('( )', ' ', cleaned_text)
|
97 |
+
cleaned_text=cleaned_text.strip()
|
98 |
+
return cleaned_text
|
99 |
+
|
100 |
+
def get_text_embedding(self, text):
|
101 |
+
input_texts = []
|
102 |
+
text = self.preprocessing_patent_data(text)
|
103 |
+
logging.info('Input Text Processed')
|
104 |
+
input_texts.append(text)
|
105 |
+
batch_dict = self.text_tokenizer (input_texts, max_length=1024, padding=True, truncation=True, return_tensors='pt').to(self.device)
|
106 |
+
if self.device == 'cuda':
|
107 |
+
with torch.autocast(device_type="cuda", dtype=torch.float16):
|
108 |
+
with torch.inference_mode():
|
109 |
+
outputs = self.text_model(**batch_dict)
|
110 |
+
else:
|
111 |
+
with torch.inference_mode():
|
112 |
+
outputs = self.text_model(**batch_dict)
|
113 |
+
embeddings = outputs.last_hidden_state[:, 0]
|
114 |
+
embeddings = F.normalize(embeddings, p=2, dim=1)
|
115 |
+
logging.info('Embd Normalized')
|
116 |
+
values = embeddings[0].tolist()
|
117 |
+
logging.info('Embd Created')
|
118 |
+
return values
|
119 |
+
|
120 |
+
model = EmbeddingModels()
|
121 |
+
logging.info('Model Loaded!')
|
122 |
+
|
123 |
+
@app.post("/embed-text-gb/")
|
124 |
+
async def embed_text(text: str = Query(...)):
|
125 |
+
try:
|
126 |
+
embeddings = model.get_text_embedding(text)
|
127 |
+
return embeddings
|
128 |
+
except Exception as e:
|
129 |
+
logging.info(f'Error: {e}')
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fastapi
|
2 |
+
uvicorn
|
3 |
+
pillow
|
4 |
+
torch
|
5 |
+
transformers
|
6 |
+
fastapi_health
|