janasumit2911 commited on
Commit
e722aa1
·
verified ·
1 Parent(s): 5c17f77

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ from transformers import BertTokenizer, TFBertForSequenceClassification
3
+ import numpy as np
4
+ import json
5
+ import requests
6
+ import gradio as gr
7
+
8
+
9
+ bert_tokenizer = BertTokenizer.from_pretrained('BinaryTokenizer_ep5')
10
+ bert_model = TFBertForSequenceClassification.from_pretained('BinaryModel_ep5')
11
+
12
+ def send_results_to_api(data, result_url):
13
+ headers = {'Content-Type':'application/json'}
14
+ response = requests.post(result_url, json = data, headers=headers)
15
+
16
+ if response.status_code == 200:
17
+ return response.json
18
+ else:
19
+ return {'error':f"failed to send result to API: {response.status_code}"}
20
+
21
+ def process_audio(params):
22
+ params = json.loads(params)
23
+
24
+ texts = params.get("texts",[])
25
+ api = params.get("api", "")
26
+ job_id = params.get("job_id","")
27
+
28
+ solutions = []
29
+
30
+ for text in texts:
31
+ encoding = bert_tokenizer.encode_plus(
32
+ text,
33
+ add_special_tokens=True,
34
+ max_length=128,
35
+ return_token_type_ids=True,
36
+ padding = 'max_length',
37
+ truncation=True,
38
+ return_attention_mask=True,
39
+ return_tensors='tf'
40
+ )
41
+ input_ids = encoding['input_ids']
42
+ token_type_ids = encoding['token_type_ids']
43
+ attention_mask = encoding['attention_mask']
44
+
45
+ pred = bert_model.predict([input_ids, token_type_ids, attention_mask])
46
+ logits = pred.logits
47
+ pred_label = tf.argmax(logits, axis=1).numpy()[0]
48
+
49
+ label = {1:'positive', 0:'negative'}
50
+ result = {'text':text, 'label':label[pred_label]}
51
+ solutions.append(result)
52
+
53
+ result_url = f"{api}/{job_id}"
54
+ send_results_to_api(solutions, result_url)
55
+ return json.dumps({"solutions":solutions}, indent=4)
56
+
57
+
58
+ inputt = gr.Textbox(label="Parameters in Json Format...")
59
+ outputt = gr.JSON()
60
+
61
+ application = gr.Interface(fn = process_audio(), inputs = inputt, outputs = outputt, title='Multi Text Classification with API Integration..')
62
+ application.launch()