thugCodeNinja commited on
Commit
4eae158
1 Parent(s): 3285621

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from torch.nn.functional import softmax
4
+ import shap
5
+ import requests
6
+ from transformers import RobertaTokenizer, pipeline, RobertaModel
7
+ model_dir = 'temp'
8
+ tokenizer = RobertaTokenizer.from_pretrained(model_dir)
9
+ model = RobertaModel.from_pretrained(model_dir)
10
+
11
+ @app.route('/gradio_app')
12
+ def gradio_app():
13
+ def process_text(input_text, input_file):
14
+ if input_text:
15
+ text = input_text
16
+ elif input_file is not None:
17
+ text = input_file.read().decode('utf-8')
18
+ inputs = tokenizer(text, return_tensors="pt")
19
+ with torch.no_grad():
20
+ logits = model(**inputs).logits
21
+ probs = softmax(logits, dim=1)
22
+ max_prob, predicted_class_id = torch.max(probs, dim=1)
23
+ prob = str(round(max_prob.item() * 100, 2))
24
+ label = model.config.id2label[predicted_class_id.item()]
25
+ final_label='Human' if model.config.id2label[predicted_class_id.item()]=='LABEL_0' else 'Chat-GPT'
26
+ processed_result = text
27
+
28
+ def search(text):
29
+ query = text
30
+ api_key = 'AIzaSyClvkiiJTZrCJ8BLqUY9I38WYmbve8g-c8'
31
+ search_engine_id = '53d064810efa44ce7'
32
+ url = f'https://www.googleapis.com/customsearch/v1?key={api_key}&cx={search_engine_id}&q={query}'
33
+
34
+ try:
35
+ response = requests.get(url)
36
+ data = response.json()
37
+ return data
38
+ except Exception as e:
39
+ return {'error': str(e)}
40
+
41
+ def find_plagiarism(text):
42
+ search_results = search(text)
43
+ if 'items' not in search_results:
44
+ return []
45
+ similar_articles = []
46
+ for item in search_results['items']:
47
+ title = item.get('title', '')
48
+ link = item.get('link', '')
49
+ similar_articles.append({'title': title, 'link': link})
50
+ return similar_articles[:5]
51
+
52
+ pipe = pipeline('text-classification', model=model, tokenizer=tokenizer)
53
+ prediction = pipe([text])
54
+ explainer = shap.Explainer(pipe)
55
+ shap_values = explainer([text])
56
+ text_plot = shap.plots.text(shap_values, display=True)
57
+ similar_articles = find_plagiarism(text)
58
+
59
+ return processed_result, prob, final_label, text_plot,similar_articles
60
+
61
+ text_input = gr.inputs.Textbox(label="Enter text")
62
+ file_input = gr.inputs.File(label="Upload a text file")
63
+ outputs = [gr.Textbox(label="Processed text"), gr.Textbox(label="Probability"), gr.Textbox(label="Label"), gr.HTML(label="SHAP Plot"),gr.Table(label="Similar Articles", columns=["Title", "Link"])]
64
+
65
+ gr.Interface(fn=process_text, inputs=[text_input, file_input], outputs=outputs).launch()
66
+
67
+ return ''
68
+
69
+ if __name__ == '__main__':
70
+ app.run(debug=True)