hashirlodhi commited on
Commit
7397765
Β·
verified Β·
1 Parent(s): 58a7c42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -69
app.py CHANGED
@@ -1,89 +1,45 @@
1
- import os
2
- import requests
3
  import gradio as gr
4
-
5
- # Load OpenRouter API key from environment variable
6
- OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
7
-
8
- if not OPENROUTER_API_KEY:
9
- raise ValueError("OPENROUTER_API_KEY environment variable not set. Please set it in your environment or deployment settings.")
10
-
11
- # OpenRouter API endpoint
12
- API_URL = "https://openrouter.ai/api/v1/chat/completions"
13
-
14
- # Using the specified Qwen model
15
- MODEL_NAME = "qwen/qwen3-235b-a22b-07-25:free"
16
 
17
  def classify_text(text):
18
  if not text.strip():
19
  return "Error: Please enter a non-empty text."
20
 
21
- # πŸ”₯ Enhanced Prompt
 
22
  prompt = f"""
23
- You are a professional text analysis specialist. Your job is to classify whether a given text was written by a human or generated by AI.
24
- You must respond with clear reasoning and high confidence β€” your answers should be rated 10/10 in accuracy and helpfulness. Be concise, accurate, and structured.
25
-
26
- Analyze the following text and return the result in the exact format:
27
-
28
- Classification: [AI-written / Human-written]
29
- Reason: [Short but strong explanation β€” logic, tone, structure, etc.]
30
-
31
- Here are a few examples to guide your judgment:
32
 
33
- Text: "The algorithm efficiently processes data to generate coherent responses."
34
- Classification: AI-written
35
- Reason: The text uses technical language and abstraction typical of AI-generated content.
36
-
37
- Text: "I went to the park and saw a beautiful sunset."
38
- Classification: Human-written
39
- Reason: Personal experience with emotional tone indicates human authorship.
40
-
41
- Text: "Artificial intelligence systems leverage neural networks to optimize performance."
42
- Classification: AI-written
43
- Reason: Overly formal and technical β€” likely AI-generated.
44
-
45
- Text: "My dog loves chasing squirrels in the backyard!"
46
- Classification: Human-written
47
- Reason: Informal and emotionally expressive β€” common in human writing.
48
-
49
- Now analyze this:
50
-
51
- Text: "{text}"
52
- Classification:
53
- Reason:
54
  """
55
-
56
- headers = {
57
- "Authorization": f"Bearer {OPENROUTER_API_KEY}",
58
- "Content-Type": "application/json",
59
- "X-Title": "AI-vs-Human-Classifier"
60
- }
61
-
62
  payload = {
63
- "model": MODEL_NAME,
64
- "messages": [
65
- {"role": "user", "content": prompt}
66
- ]
 
67
  }
68
-
69
  try:
70
- response = requests.post(API_URL, headers=headers, json=payload)
71
  response.raise_for_status()
72
  result = response.json()
73
- return result["choices"][0]["message"]["content"].strip()
 
 
 
 
 
74
  except Exception as e:
75
- return f"Error: {str(e)}\nTip: Make sure the API key and model name are correct."
76
 
77
- # Gradio interface
78
  iface = gr.Interface(
79
  fn=classify_text,
80
- inputs=gr.Textbox(lines=5, placeholder="Paste text to classify...", label="Text Input"),
81
- outputs=gr.Textbox(label="Classification Result"),
82
- title="πŸ€– AI vs Human Text Classifier (Qwen)",
83
- description="Detect if your text is AI-generated or Human-written using Qwen model via OpenRouter API.\nMake sure OPENROUTER_API_KEY is set in your environment.",
84
- allow_flagging="never"
85
  )
86
 
87
- # Launch the Gradio app
88
- if __name__ == "__main__":
89
- iface.launch()
 
 
 
1
  import gradio as gr
2
+ import requests
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  def classify_text(text):
5
  if not text.strip():
6
  return "Error: Please enter a non-empty text."
7
 
8
+ API_URL = "https://api-inference.huggingface.co/models/facebook/bart-large-mnli"
9
+
10
  prompt = f"""
11
+ Classify whether this text was written by a human or generated by AI. Respond with either "AI-written" or "Human-written" and a brief reason.
 
 
 
 
 
 
 
 
12
 
13
+ Text: "{text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  """
15
+
 
 
 
 
 
 
16
  payload = {
17
+ "inputs": prompt,
18
+ "parameters": {
19
+ "candidate_labels": ["AI-written", "Human-written"],
20
+ "multi_label": False
21
+ }
22
  }
23
+
24
  try:
25
+ response = requests.post(API_URL, json=payload)
26
  response.raise_for_status()
27
  result = response.json()
28
+
29
+ if 'labels' in result and 'scores' in result:
30
+ label = result['labels'][0]
31
+ score = result['scores'][0]
32
+ return f"Classification: {label}\nConfidence: {score:.0%}"
33
+ return str(result)
34
  except Exception as e:
35
+ return f"Error: {str(e)}"
36
 
 
37
  iface = gr.Interface(
38
  fn=classify_text,
39
+ inputs=gr.Textbox(lines=5, placeholder="Paste text to classify..."),
40
+ outputs=gr.Textbox(label="Result"),
41
+ title="πŸ€– Simple AI vs Human Classifier",
42
+ description="Basic classifier using a free Hugging Face model (no API key needed)"
 
43
  )
44
 
45
+ iface.launch()