saneowl commited on
Commit
ef92b60
·
verified ·
1 Parent(s): 01cff1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -24
app.py CHANGED
@@ -1,25 +1,33 @@
1
  import gradio as gr
2
- from transformers import RobertaTokenizer, RobertaForSequenceClassification
 
 
 
3
  import torch
4
 
5
- # Define available models
6
  model_options = {
7
  "GoalZero/aidetection-ada-v0.2": "GoalZero/aidetection-ada-v0.2",
8
  "GoalZero/aidetection-ada-v0.1": "GoalZero/aidetection-ada-v0.1",
9
- "GoalZero/babbage-mini-v0.1": "GoalZero/babbage-mini-v0.1"
 
10
  }
11
 
12
- # Initialize global variables for model and tokenizer
13
  model = None
14
  tokenizer = None
 
15
 
16
  def load_model(model_name):
17
- """Helper function to load model and tokenizer"""
18
  try:
19
- return (
20
- RobertaForSequenceClassification.from_pretrained(model_name),
21
- RobertaTokenizer.from_pretrained(model_name)
22
- )
 
 
 
23
  except Exception as e:
24
  raise Exception(f"Failed to load model {model_name}: {str(e)}")
25
 
@@ -27,21 +35,23 @@ def load_model(model_name):
27
  try:
28
  default_model = "GoalZero/aidetection-ada-v0.2"
29
  model, tokenizer = load_model(default_model)
 
30
  except Exception as e:
31
  print(f"Error loading default model: {str(e)}")
32
 
33
  def classify_text(text, model_choice):
34
- global model, tokenizer
35
 
36
  try:
37
- # Check if we need to change the model
38
- if model is None or model_choice != model.name_or_path:
39
  model, tokenizer = load_model(model_choice)
 
40
 
41
- # Clean the input text
42
  cleaned_text = text.replace('.', '').replace('\n', ' ')
43
 
44
- # Tokenize the cleaned input text
45
  inputs = tokenizer(
46
  cleaned_text,
47
  return_tensors='pt',
@@ -50,21 +60,16 @@ def classify_text(text, model_choice):
50
  max_length=128
51
  )
52
 
53
- # Get the model's prediction
54
  with torch.no_grad():
55
  outputs = model(**inputs)
56
-
57
- # Apply softmax to get probabilities
58
  probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
59
-
60
- # Get the probability of class '1'
61
- prob_1 = probabilities[0][1].item()
62
 
63
  return {
64
- "AI Probability": round(prob_1 * 100, 10),
65
  "Model used": model_choice
66
  }
67
-
68
  except Exception as e:
69
  return {
70
  "error": f"An error occurred: {str(e)}",
@@ -92,10 +97,11 @@ iface = gr.Interface(
92
  examples=[
93
  ["Waymo is an American autonomous driving technology company that originated as the Google Self-Driving Car Project in 2009. It is now a subsidiary of Alphabet Inc., headquartered in Mountain View, California. The name \"Waymo\" was adopted in December 2016 when the project was rebranded and spun out of Google to focus on developing fully autonomous vehicles aimed at improving transportation safety and convenience", "GoalZero/babbage-mini-v0.1"],
94
  ["WWII demonstrated the importance of alliances in global conflicts. The Axis and Allied powers were formed as countries sought to protect their interests and expand their influence. This lesson underscores the potential for future global conflicts to involve complex alliances, similar to the Cold War era’s NATO and Warsaw Pact alignments.", "GoalZero/aidetection-ada-v0.2"],
95
- ["Eustace was a thorough gentleman. There was candor in his quack, and affability in his waddle; and underneath his snowy down beat a pure and sympathetic heart. In short, he was a most exemplary duck.", "GoalZero/aidetection-ada-v0.1"]
 
96
  ]
97
  )
98
 
99
  # Launch the app
100
  if __name__ == "__main__":
101
- iface.launch(share=True)
 
1
  import gradio as gr
2
+ from transformers import (
3
+ RobertaTokenizer, RobertaForSequenceClassification,
4
+ AutoTokenizer, AutoModelForSequenceClassification
5
+ )
6
  import torch
7
 
8
+ # Define available models including DeBERTa
9
  model_options = {
10
  "GoalZero/aidetection-ada-v0.2": "GoalZero/aidetection-ada-v0.2",
11
  "GoalZero/aidetection-ada-v0.1": "GoalZero/aidetection-ada-v0.1",
12
+ "GoalZero/babbage-mini-v0.1": "GoalZero/babbage-mini-v0.1",
13
+ "GoalZero/ada-2534": "GoalZero/ada-2534"
14
  }
15
 
16
+ # Initialize global variables
17
  model = None
18
  tokenizer = None
19
+ current_model_name = None
20
 
21
  def load_model(model_name):
22
+ """Load model and tokenizer, handling both RoBERTa and DeBERTa"""
23
  try:
24
+ if "deberta" in model_name.lower() or "ada-2534" in model_name.lower():
25
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
26
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
27
+ else:
28
+ model = RobertaForSequenceClassification.from_pretrained(model_name)
29
+ tokenizer = RobertaTokenizer.from_pretrained(model_name)
30
+ return model, tokenizer
31
  except Exception as e:
32
  raise Exception(f"Failed to load model {model_name}: {str(e)}")
33
 
 
35
  try:
36
  default_model = "GoalZero/aidetection-ada-v0.2"
37
  model, tokenizer = load_model(default_model)
38
+ current_model_name = default_model
39
  except Exception as e:
40
  print(f"Error loading default model: {str(e)}")
41
 
42
  def classify_text(text, model_choice):
43
+ global model, tokenizer, current_model_name
44
 
45
  try:
46
+ # Reload model if needed
47
+ if model is None or model_choice != current_model_name:
48
  model, tokenizer = load_model(model_choice)
49
+ current_model_name = model_choice
50
 
51
+ # Clean input
52
  cleaned_text = text.replace('.', '').replace('\n', ' ')
53
 
54
+ # Tokenize
55
  inputs = tokenizer(
56
  cleaned_text,
57
  return_tensors='pt',
 
60
  max_length=128
61
  )
62
 
63
+ # Predict
64
  with torch.no_grad():
65
  outputs = model(**inputs)
 
 
66
  probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
67
+ prob_ai = probabilities[0][1].item()
 
 
68
 
69
  return {
70
+ "AI Probability": round(prob_ai * 100, 10),
71
  "Model used": model_choice
72
  }
 
73
  except Exception as e:
74
  return {
75
  "error": f"An error occurred: {str(e)}",
 
97
  examples=[
98
  ["Waymo is an American autonomous driving technology company that originated as the Google Self-Driving Car Project in 2009. It is now a subsidiary of Alphabet Inc., headquartered in Mountain View, California. The name \"Waymo\" was adopted in December 2016 when the project was rebranded and spun out of Google to focus on developing fully autonomous vehicles aimed at improving transportation safety and convenience", "GoalZero/babbage-mini-v0.1"],
99
  ["WWII demonstrated the importance of alliances in global conflicts. The Axis and Allied powers were formed as countries sought to protect their interests and expand their influence. This lesson underscores the potential for future global conflicts to involve complex alliances, similar to the Cold War era’s NATO and Warsaw Pact alignments.", "GoalZero/aidetection-ada-v0.2"],
100
+ ["Eustace was a thorough gentleman. There was candor in his quack, and affability in his waddle; and underneath his snowy down beat a pure and sympathetic heart. In short, he was a most exemplary duck.", "GoalZero/aidetection-ada-v0.1"],
101
+ ["This is an example of AI-written text using the DeBERTa model for testing purposes.", "GoalZero/ada-2534"]
102
  ]
103
  )
104
 
105
  # Launch the app
106
  if __name__ == "__main__":
107
+ iface.launch(share=True)