D3V1L1810 commited on
Commit
ea325b8
·
verified ·
1 Parent(s): 07a3f22

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +70 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ try:
25
+ params = json.loads(params)
26
+ except Exception as e:
27
+ return {"error": f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}"}
28
+
29
+ texts = params.get("texts", [])
30
+ # api = params.get("api", "")
31
+ # job_id = params.get("job_id", "")
32
+
33
+ if not texts:
34
+ return { "error": f"Invalid JSON input {e.msg} at line {e.lineno} column {e.colno}"}
35
+
36
+ solutions = []
37
+
38
+ for text in texts:
39
+ encoding = bert_tokenizer.encode_plus(
40
+ text,
41
+ add_special_tokens=True,
42
+ max_length=128,
43
+ return_token_type_ids=True,
44
+ padding='max_length',
45
+ truncation=True,
46
+ return_attention_mask=True,
47
+ return_tensors='tf'
48
+ )
49
+ input_ids = encoding['input_ids']
50
+ token_type_ids = encoding['token_type_ids']
51
+ attention_mask = encoding['attention_mask']
52
+
53
+ pred = bert_model.predict([input_ids, token_type_ids, attention_mask])
54
+ logits = pred.logits
55
+ pred_label = tf.argmax(logits, axis=1).numpy()[0]
56
+
57
+ label = {1: 'positive', 0: 'negative'}
58
+ result = {'text': text, 'label': [label[pred_label]]}
59
+ solutions.append(result)
60
+
61
+ # result_url = f"{api}/{job_id}"
62
+ # send_results_to_api(solutions, result_url)
63
+ return json.dumps({"solutions": solutions})
64
+
65
+
66
+ inputt = gr.Textbox(label="Parameter in JSON format (e.g., {'texts': ['sample text', 'sample text2']'})")
67
+ outputt = gr.JSON()
68
+
69
+ application = gr.Interface(fn=predict_text, inputs=inputt, outputs=outputt, title="Text Classification with BERT and API Integration")
70
+ application.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ tensorflow
2
+ transformers
3
+ tf-keras