janasumit2911 commited on
Commit
d7a781f
·
verified ·
1 Parent(s): 0b9d42d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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') #path + '/BinaryTokenizer_ep5'
10
+ bert_model = TFBertForSequenceClassification.from_pretrained('BinaryModel_ep5')
11
+
12
+
13
+ def send_results_to_api(data, result_url):
14
+ headers = {"Content-Type":"application/json"}
15
+ response = requests.post(result_url, json=data, headers=headers)
16
+
17
+ if response.status_code == 200:
18
+ return response.json()
19
+ else:
20
+ return {"error": f"Failed to send results to API: {response.status_code}"}
21
+
22
+
23
+ def predict_text(params):
24
+ params = json.loads(params)
25
+
26
+ texts = params.get("texts", [])
27
+ api = params.get("api", "")
28
+ job_id = params.get("job_id", "")
29
+
30
+ solutions = []
31
+
32
+ for text in texts:
33
+ encoding = bert_tokenizer.encode_plus(
34
+ text,
35
+ add_special_tokens=True,
36
+ max_length=128,
37
+ return_token_type_ids=True,
38
+ padding='max_length',
39
+ truncation=True,
40
+ return_attention_mask=True,
41
+ return_tensors='tf'
42
+ )
43
+ input_ids = encoding['input_ids']
44
+ token_type_ids = encoding['token_type_ids']
45
+ attention_mask = encoding['attention_mask']
46
+
47
+ pred = bert_model.predict([input_ids, token_type_ids, attention_mask])
48
+ logits = pred.logits
49
+ pred_label = tf.argmax(logits, axis=1).numpy()[0]
50
+
51
+ label = {1: 'positive', 0: 'negative'}
52
+ result = {'text': text, 'label': label[pred_label]}
53
+ solutions.append(result)
54
+
55
+ result_url = f"{api}/{job_id}"
56
+ # send_results_to_api(solutions, result_url)
57
+ return json.dumps({"solutions": solutions}, indent=4)
58
+
59
+
60
+ inputt = gr.Textbox(label="Parameter in JSON format (e.g., {'texts': ['sample text', 'sample text2'], 'api': 'https://api.example.com', 'job_id': '1001'})")
61
+ outputt = gr.JSON()
62
+
63
+ application = gr.Interface(fn=predict_text, inputs=inputt, outputs=outputt, title="Text Classification with BERT and API Integration")
64
+ application.launch()