thepolymerguy commited on
Commit
2c84034
·
1 Parent(s): ea166a3

Delete old_version.py

Browse files
Files changed (1) hide show
  1. old_version.py +0 -485
old_version.py DELETED
@@ -1,485 +0,0 @@
1
- import os
2
- import gradio as gr
3
- import pandas as pd
4
- import torch
5
- import torch.nn as nn
6
- import transformers
7
- from transformers import AutoTokenizer, AutoConfig, LlamaForCausalLM, LlamaTokenizer, GenerationConfig, AutoModel, pipeline
8
- import pandas as pd
9
- import tensorflow as tf
10
- import numpy as np
11
- import math
12
- import time
13
- import csv
14
- import nltk
15
- from nltk.tokenize import word_tokenize
16
- from nltk.corpus import stopwords
17
- nltk.download('stopwords')
18
- nltk.download('punkt')
19
- import string
20
-
21
- ########### Import Classifier Embeddings #########
22
- class_embeddings = pd.read_csv('Embeddings/MainClassEmbeddings.csv')
23
-
24
- ########### DATA CLEANER VARIABLES #############
25
- all_stopwords = stopwords.words('english') # Making sure to only use English stopwords
26
- extra_stopwords = ['ii', 'iii'] # Can add extra stopwords to be removed from dataset/input abstracts
27
- all_stopwords.extend(extra_stopwords)
28
-
29
- modelpath = os.environ.get("MODEL_PATH")
30
- ########### GET CLAIMED TRAINED MODEL ###########
31
- tokenizer = LlamaTokenizer.from_pretrained(modelpath)
32
-
33
- model = LlamaForCausalLM.from_pretrained(
34
- modelpath,
35
- load_in_8bit=True,
36
- device_map='auto',
37
- )
38
-
39
- ########## DEFINING FUNCTIONS ###################
40
-
41
- def mean_pooling(model_output, attention_mask):
42
- token_embeddings = model_output[0]
43
- input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
44
- return tf.reduce_sum(token_embeddings * input_mask_expanded, 1) / tf.clip_by_value(input_mask_expanded.sum(1), clip_value_min=1e-9, clip_value_max=math.inf)
45
-
46
- def broad_scope_class_predictor(class_embeddings, abstract_embedding, SearchType, N=5, Sensitivity='Medium'):
47
- predictions = pd.DataFrame(columns=['Class Name', 'Score'])
48
- for i in range(len(class_embeddings)):
49
- class_name = class_embeddings.iloc[i, 0]
50
- embedding = class_embeddings.iloc[i, 2]
51
- embedding = convert_saved_embeddings(embedding)
52
- abstract_embedding = abstract_embedding.numpy()
53
- abstract_embedding = torch.from_numpy(abstract_embedding)
54
- cos = torch.nn.CosineSimilarity(dim=1)
55
- score = cos(abstract_embedding, embedding).numpy().tolist()
56
- result = [class_name, score[0]]
57
- predictions.loc[len(predictions)] = result
58
- if Sensitivity == 'High':
59
- Threshold = 0.5
60
- elif Sensitivity == 'Medium':
61
- Threshold = 0.40
62
- elif Sensitivity == 'Low':
63
- Threshold = 0.35
64
- GreenLikelihood = 'False'
65
- HighestSimilarity = predictions.nlargest(N, ['Score'])
66
- HighestSimilarity = HighestSimilarity['Class Name'].tolist()
67
- HighestSimilarityClass = [x.split('/')[0] for x in HighestSimilarity]
68
- if SearchType == 'Google Patent Search':
69
- Links = [f'https://patents.google.com/?q=({x}%2f00)&oq={x}%2f00' for x in HighestSimilarityClass]
70
- elif SearchType == 'Espacenet Patent Search':
71
- Links = [f'https://worldwide.espacenet.com/patent/search?q=cpc%3D{x}%2F00%2Flow' for x in HighestSimilarityClass]
72
- HighestSimilarity = pd.DataFrame({'Class':HighestSimilarity})
73
- return HighestSimilarity
74
-
75
-
76
- def sentence_embedder(sentences, model_path):
77
- tokenizer = AutoTokenizer.from_pretrained(model_path) #instantiating the sentence embedder using HuggingFace library
78
- model = AutoModel.from_pretrained(model_path, from_tf=True) #making a model instance
79
- encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
80
- # Compute token embeddings
81
- with torch.no_grad():
82
- model_output = model(**encoded_input)
83
- sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask']) #outputs a (1, 384) tensor representation of input text
84
- return sentence_embeddings
85
-
86
-
87
- def add_text(history, text):
88
- history = history + [(text, None)]
89
- return history, ""
90
-
91
-
92
- def convert_saved_embeddings(embedding_string):
93
- """
94
- Preparing pre-computed embeddings for use for comparison with new abstract embeddings .
95
- Pre-computed embeddings are saved as tensors in string format so need to be converted back to numpy arrays in order to calculate cosine similarity.
96
- :param embedding_string:
97
- :return: Should be a single tensor with dims (,384) in string format
98
- """
99
- embedding = embedding_string.replace('(', '')
100
- embedding = embedding.replace(')', '')
101
- embedding = embedding.replace('[', '')
102
- embedding = embedding.replace(']', '')
103
- embedding = embedding.replace('tensor', '')
104
- embedding = embedding.replace(' ', '')
105
- embedding = embedding.split(',')
106
- embedding = [float(x) for x in embedding]
107
- embedding = np.array(embedding)
108
- embedding = np.expand_dims(embedding, axis=0)
109
- embedding = torch.from_numpy(embedding)
110
- return embedding
111
-
112
- ########## LOADING PRE-COMPUTED EMBEDDINGS ##########
113
-
114
- def clean_data(input, type='Dataframe'):
115
- if type == 'Dataframe':
116
- cleaneddf = pd.DataFrame(columns=['Class', 'Description'])
117
- for i in range(0, len(input)):
118
- row_list = input.loc[i, :].values.flatten().tolist()
119
- noNaN_row = [x for x in row_list if str(x) != 'nan']
120
- listrow = []
121
- if len(noNaN_row) > 0:
122
- row = noNaN_row[:-1]
123
- row = [x.strip() for x in row]
124
- row = (" ").join(row)
125
- text_tokens = word_tokenize(row) # splits abstracts into individual tokens to allow removal of stopwords by list comprehension
126
- Stopword_Filtered_List = [word for word in text_tokens if not word in all_stopwords] # removes stopwords
127
- row = (" ").join(Stopword_Filtered_List) # returns abstract to string form
128
- removechars = ['[', ']', '{', '}', ';', '(', ')', ',', '.', ':', '/', '-', '#', '?', '@', '£', '$']
129
- for char in removechars:
130
- row = list(map(lambda x: x.replace(char, ''), row))
131
-
132
- row = ''.join(row)
133
- wnum = row.split(' ')
134
- wnum = [x.lower() for x in wnum]
135
- #remove duplicate words
136
- wnum = list(dict.fromkeys(wnum))
137
- #removing numbers
138
- wonum = []
139
- for x in wnum:
140
- xv = list(x)
141
- xv = [i.isnumeric() for i in xv]
142
- if True in xv:
143
- continue
144
- else:
145
- wonum.append(x)
146
- row = ' '.join(wonum)
147
- l = [noNaN_row[-1], row]
148
- cleaneddf.loc[len(cleaneddf)] = l
149
- cleaneddf = cleaneddf.drop_duplicates(subset=['Description'])
150
- cleaneddf.to_csv('E:/Users/eeo21/Startup/CPC_Classifications_List/additionalcleanedclasses.csv', index=False)
151
- return cleaneddf
152
-
153
- elif type == 'String':
154
- text_tokens = word_tokenize(input) # splits abstracts into individual tokens to allow removal of stopwords by list comprehension
155
- Stopword_Filtered_List = [word for word in text_tokens if not word in all_stopwords] # removes stopwords
156
- row = (" ").join(Stopword_Filtered_List) # returns abstract to string form
157
- removechars = ['[', ']', '{', '}', ';', '(', ')', ',', '.', ':', '/', '-', '#', '?', '@', '£', '$']
158
- for char in removechars:
159
- row = list(map(lambda x: x.replace(char, ''), row))
160
- row = ''.join(row)
161
- wnum = row.split(' ')
162
- wnum = [x.lower() for x in wnum]
163
- # remove duplicate words
164
- wnum = list(dict.fromkeys(wnum))
165
- # removing numbers
166
- wonum = []
167
- for x in wnum:
168
- xv = list(x)
169
- xv = [i.isnumeric() for i in xv]
170
- if True in xv:
171
- continue
172
- else:
173
- wonum.append(x)
174
- row = ' '.join(wonum)
175
- return row
176
-
177
- def classifier(userin, SearchType):
178
- clean_in = clean_data(userin, type='String')
179
- in_emb = sentence_embedder(clean_in, 'Model_bert')
180
-
181
- Number = 10
182
- broad_scope_predictions = broad_scope_class_predictor(class_embeddings, in_emb, SearchType, Number, Sensitivity='High')
183
-
184
- return broad_scope_predictions
185
-
186
- def generateresponse(history, temp, top_p, tokens):
187
-
188
- global model
189
- global tokenizer
190
-
191
- user = history[-1][0]
192
-
193
- PROMPT = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
194
- ### Instruction:
195
- {user}
196
- ### Response:"""
197
-
198
- pipe = pipeline(
199
- "text-generation",
200
- model=model,
201
- tokenizer=tokenizer,
202
- max_length=2048,
203
- temperature=temp,
204
- top_p=top_p,
205
- repetition_penalty=1.15
206
- )
207
-
208
- outputs = pipe(PROMPT)
209
- outputs = outputs[0]['generated_text']
210
- outputs = str(outputs).split('### Response')[1]
211
-
212
- response = f"Response{outputs}"
213
- return response
214
-
215
- def run_model(userin, dropd):
216
-
217
- global model
218
- global tokenizer
219
-
220
- if dropd in ["An apparatus", "A method of use", "A method", "A method of making", "A system"]:
221
- PROMPT = claim_selector(userin, dropd)
222
- elif dropd in ["Generate a Detailed Description Paragraph", "Generate a Abstract", "What are the Benefits/Technical Effects"]:
223
- PROMPT = desc_selector(userin, dropd)
224
-
225
- pipe = pipeline(
226
- "text-generation",
227
- model=model,
228
- tokenizer=tokenizer,
229
- max_length=2048,
230
- temperature=0.7,
231
- top_p=0.95,
232
- repetition_penalty=1.15
233
- )
234
-
235
- outputs = pipe(PROMPT)
236
-
237
- outputs = outputs[0]['generated_text']
238
- outputs = str(outputs).split('### Response')[1]
239
- outputs = outputs.split('\n \n \n \n*')[0]
240
-
241
- response = f"Response{outputs}"
242
- return response
243
-
244
- def prosecute(application, priorart):
245
-
246
- global model
247
- global tokenizer
248
-
249
- pipe = pipeline(
250
- "text-generation",
251
- model=model,
252
- tokenizer=tokenizer,
253
- max_length=2048,
254
- temperature=0.7,
255
- top_p=0.95,
256
- repetition_penalty=1.15
257
- )
258
-
259
- PROMPT = f"""
260
- Draft an argument for the patentability in favour of the application using the European Patent Office Problem Solution. Start by summarising the difference between the application and the prior art:
261
-
262
- Application: {application}
263
-
264
- Prior Art: {priorart}
265
-
266
- ### Response: The objective technical problem solved by the present invention"""
267
-
268
- outputs = pipe(PROMPT)
269
-
270
- outputs = outputs[0]['generated_text']
271
- outputs = str(outputs).split('### Response')[1]
272
- outputs = outputs.split('\n \n \n \n*')[0]
273
-
274
- response = f"Response{outputs}"
275
- return response
276
-
277
- def ideator(userin):
278
-
279
- global model
280
- global tokenizer
281
-
282
- pipe = pipeline(
283
- "text-generation",
284
- model=model,
285
- tokenizer=tokenizer,
286
- max_length=2048,
287
- temperature=0.7,
288
- top_p=0.95,
289
- repetition_penalty=1.15
290
- )
291
-
292
- PROMPT = f"""
293
- How can I make {userin}
294
-
295
- ### Response: You could implement the invention as follows:"""
296
-
297
- outputs = pipe(PROMPT)
298
-
299
- outputs = outputs[0]['generated_text']
300
- outputs = str(outputs).split('### Response')[1]
301
- outputs = outputs.split('\n \n \n \n*')[0]
302
-
303
-
304
- response = f"Response{outputs}"
305
- return response
306
-
307
- def Chat(userin):
308
-
309
- global model
310
- global tokenizer
311
-
312
- pipe = pipeline(
313
- "text-generation",
314
- model=model,
315
- tokenizer=tokenizer,
316
- max_length=2048,
317
- temperature=0.7,
318
- top_p=0.95,
319
- repetition_penalty=1.15
320
- )
321
-
322
- PROMPT = f"""Below is a query from a user. Respond appropriately to the query.
323
- ### Query:
324
- {userin}
325
- ### Response:"""
326
-
327
- outputs = pipe(PROMPT)
328
-
329
- outputs = outputs[0]['generated_text']
330
- outputs = str(outputs).split('### Response')[1]
331
- outputs = outputs.split('\n \n \n \n*')[0]
332
-
333
- response = f"Response{outputs}"
334
- return response
335
-
336
- def claim_selector(userin, dropd):
337
-
338
- PROMPT = f"""
339
- Draft a patent claim 1 for {dropd} for the following invention: {userin}
340
- ### Response:{dropd} comprising:"""
341
-
342
- return PROMPT
343
-
344
- def desc_selector(userin, dropd):
345
-
346
- PROMPT = f"""
347
- {dropd} for a patent application for the following invention: {userin}
348
- ### Response:"""
349
-
350
- return PROMPT
351
-
352
- ############# GRADIO APP ###############
353
-
354
- theme = gr.themes.Base(
355
- primary_hue="indigo",
356
- ).set(
357
- prose_text_size='*text_sm'
358
- )
359
-
360
- with gr.Blocks(title='Claimed', theme=theme) as demo:
361
- gr.Markdown("""
362
- # CLAIMED - A GENERATIVE TOOLKIT FOR PATENT ATTORNEYS AND INVENTORS
363
- The patenting process can be complex, time-consuming and expensive. We believe that AI will one day solve these problems.
364
-
365
- Welcome to our demo! We've trained Meta's Llama on over 200k entries, with a focus on tasks related to the intellectual property domain.
366
- Please note that this is for research purposes and shouldn't be used commercially.
367
- None of the outputs of this model, taken in part or in its entirety, constitutes legal advice. If you are seeking protection for you intellectual property, consult a registered patent/trademark attorney.
368
- """)
369
-
370
- with gr.Tab("Ideator"):
371
- gr.Markdown("""
372
- Use this tool to generate ideas!
373
- """)
374
- with gr.Row(scale=1, min_width=600):
375
- with gr.Column():
376
- userin = gr.Text(label="Input", lines=5)
377
- with gr.Column():
378
- text2 = gr.Textbox(label="Output", lines=5)
379
- with gr.Row():
380
- btn = gr.Button("Submit")
381
- btn.click(fn=ideator, inputs=[userin], outputs=text2)
382
-
383
- with gr.Tab("Claim Drafter"):
384
- gr.Markdown("""
385
- Use this tool to expand your idea into the technical language of a patent claim. You can specify the type of claim you want using the dropdown menu.
386
- """)
387
- Claimchoices = gr.Dropdown(["An apparatus", "A method of use", "A method", "A method of making", "A system"], label='Choose Claim Type Here')
388
-
389
- with gr.Row(scale=1, min_width=600):
390
- text1 = gr.Textbox(label="Input",
391
- placeholder='Type in your idea here!', lines=5)
392
- text2 = gr.Textbox(label="Output", lines=5)
393
- with gr.Row():
394
- btn = gr.Button("Submit")
395
- btn.click(fn=claim_selector, inputs=[text1, Claimchoices]).then(run_model, inputs=[text1, Claimchoices], outputs=text2)
396
-
397
- with gr.Tab("Description Generator"):
398
- gr.Markdown("""
399
- Use this tool to expand your patent claim into a description. You can also use this tool to generate abstracts and give you ideas about the benefit of an invention by changing the settings in the dropdown menu.
400
- """)
401
- Descriptionchoices = gr.Dropdown(["Generate a Detailed Description Paragraph", "Generate a Abstract", "What are the Benefits/Technical Effects"], label='Choose Generation Type Here')
402
- with gr.Row(scale=1, min_width=600):
403
-
404
- text1 = gr.Textbox(label="Input",
405
- placeholder='Type in your idea here!', lines=5)
406
- text2 = gr.Textbox(label="Output", lines=5)
407
- with gr.Row():
408
- btn = gr.Button("Submit")
409
- btn.click(fn=desc_selector, inputs=[text1, Descriptionchoices]).then(run_model, inputs=[text1, Descriptionchoices], outputs=text2)
410
-
411
- with gr.Tab("Prosecution Beta"):
412
- gr.Markdown("""
413
- Use this tool to generate ideas for how to overcome objections to novelty and inventive step. For now, this tool only works on relatively short inputs, so maybe try with some simple claims or short paragraphs.
414
- """)
415
- with gr.Row(scale=1, min_width=600):
416
- with gr.Column():
417
- application = gr.Text(label="Present Invention", lines=5)
418
- priorart = gr.Text(label="Prior Art Document", lines=5)
419
- with gr.Column():
420
- text2 = gr.Textbox(label="Output", lines=5)
421
- with gr.Row():
422
- btn = gr.Button("Submit")
423
- btn.click(fn=prosecute, inputs=[application, priorart], outputs=text2)
424
-
425
- with gr.Tab("CPC Search Tool"):
426
- gr.Markdown("""
427
- Use this tool to classify your invention according to the Cooperative Patent Classification system.
428
- Click on the link to initiate either an Espacenet or Google Patents classification search using the generated classifications. You can specify which you would like using the dropdown menu.
429
- """)
430
-
431
- ClassifyChoices = gr.Dropdown(["Google Patent Search", "Espacenet Patent Search"], label='Choose Search Type Here')
432
- with gr.Row(scale=1, min_width=600):
433
- userin = gr.Textbox(label="Input", placeholder='Type in your Claim/Description/Abstract Here',lines=5)
434
- output = gr.Textbox(label="Output", lines=5)
435
- with gr.Row():
436
- classify_btn = gr.Button("Classify")
437
- classify_btn.click(fn=classifier, inputs=[userin, ClassifyChoices] , outputs=output)
438
-
439
- with gr.Tab("Chat"):
440
- gr.Markdown("""
441
- Do you want a bit more freedom over the outputs you generate? No problem! You can use a chatbot version of our model below. You can ask it anything.
442
- If you're concerned about a particular output, hit the flag button and we will use that information to improve the model.
443
- """)
444
- with gr.Row(scale=1, min_width=600):
445
- with gr.Column():
446
- userin = gr.Text(label="Question", lines=5)
447
- with gr.Column():
448
- text2 = gr.Textbox(label="Answer", lines=5)
449
- with gr.Row():
450
- btn = gr.Button("Submit")
451
- btn.click(fn=Chat, inputs=[userin], outputs=text2)
452
-
453
- # gr.Markdown("""
454
- # # THE CHATBOT
455
- # Do you want a bit more freedom over the outputs you generate? No problem! You can use a chatbot version of our model below. You can ask it anything.
456
- # If you're concerned about a particular output, hit the flag button and we will use that information to improve the model.
457
- # """)
458
-
459
- # chatbot = gr.Chatbot([], elem_id="Claimed Assistant").style(height=500)
460
- # with gr.Row():
461
- # with gr.Column(scale=1):
462
- # txt = gr.Textbox(
463
- # show_label=False,
464
- # placeholder="Enter text and submit",
465
- # ).style(container=False)
466
- #
467
- # with gr.Row():
468
- # with gr.Accordion("Parameters"):
469
- # temp = gr.Slider(minimum=0, maximum=1, value=0.6, label="Temperature", step=0.1)
470
- # top_p = gr.Slider(minimum=0.5, maximum=1, value=0.95, label="Top P", step=0.1)
471
- # tokens = gr.Slider(minimum=5, maximum=1024, value=256, label="Max Tokens", step=1)
472
- #
473
- # txt.submit(add_text, [chatbot, txt], [chatbot, txt]).then(
474
- # generateresponse, [chatbot, temp, top_p, tokens], chatbot)
475
-
476
- gr.Markdown("""
477
- # HAVE AN IDEA? GET IT CLAIMED
478
- In the future, we are looking to expand our model's capabilities further to assist in a range of IP related tasks.
479
- If you are interested in using a more powerful model that we have trained, or if you have any suggestions of features you would like to see us add, please get in touch!
480
- As far as data is concerned, you have nothing to worry about! We don't store any of your inputs to use for further training, we're not OpenAI.
481
-
482
- """)
483
- demo.queue(max_size=15)
484
- demo.launch(share=True)
485
-