hashirlodhi commited on
Commit
2d3b82a
·
verified ·
1 Parent(s): e7aee1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -15
app.py CHANGED
@@ -30,14 +30,22 @@ def extract_features(text: str) -> Dict[str, float]:
30
  "punctuation_ratio": punctuation_ratio
31
  }
32
 
33
- def analyze_text_with_ollama(text: str) -> Dict[str, float]:
34
- """Use Llama 3.1 8B to analyze text and estimate AI vs human likelihood."""
35
  prompt = f"""
36
- You are an expert in distinguishing AI-generated text from human-written text.
37
- Analyze the following text and provide a probability (0 to 1) that it is AI-generated.
38
- Look for signs like repetitive phrasing, unnatural transitions, or overly formal tone for AI text,
39
- and creative, varied, or contextually nuanced patterns for human text.
40
- Return the result as a JSON object with a single key 'ai_probability' and a float value.
 
 
 
 
 
 
 
 
41
  Text: {text}
42
  """
43
  try:
@@ -50,17 +58,21 @@ def analyze_text_with_ollama(text: str) -> Dict[str, float]:
50
  return result
51
  except Exception as e:
52
  print(f"Error in Ollama analysis: {e}")
53
- return {"ai_probability": 0.5} # Default to neutral if model fails
 
 
 
 
54
 
55
  def classify_text(text: str) -> str:
56
- """Classify text as AI or human-written based on features and LLM analysis."""
57
  if not text or not text.strip():
58
- return "Error: No text provided."
59
-
60
  features = extract_features(text)
61
  ollama_result = analyze_text_with_ollama(text)
62
 
63
- # Combine features and LLM output (simple weighted average for demo)
64
  ai_score = ollama_result["ai_probability"]
65
  if features["word_diversity"] < 0.3: # Low diversity often indicates AI
66
  ai_score += 0.1
@@ -72,16 +84,32 @@ def classify_text(text: str) -> str:
72
  # Cap the score between 0 and 1
73
  ai_score = min(max(ai_score, 0.0), 1.0)
74
 
75
- return f"The text is likely {'AI-generated' if ai_score > 0.5 else 'Human-written'} (AI probability: {ai_score:.2f})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  def main():
78
  """Launch Gradio interface for text analysis."""
79
  iface = gr.Interface(
80
  fn=classify_text,
81
  inputs=gr.Textbox(lines=10, placeholder="Enter your text here...", label="Input Text"),
82
- outputs="text",
83
  title="AI vs Human Text Classifier",
84
- description="Enter text to determine if it's likely AI-generated or human-written using Llama 3.1 8B and linguistic features."
85
  )
86
  iface.launch(server_name="0.0.0.0", server_port=7860)
87
 
 
30
  "punctuation_ratio": punctuation_ratio
31
  }
32
 
33
+ def analyze_text_with_ollama(text: str) -> Dict[str, any]:
34
+ """Use Llama 3.1 8B to analyze text and estimate AI vs human likelihood with reasons."""
35
  prompt = f"""
36
+ You are a Text Analysis Expert with advanced capabilities in distinguishing AI-generated text from human-written text. Your task is to analyze the provided text and determine whether it is AI-generated or human-written. Consider linguistic patterns such as:
37
+ - Repetitive phrasing or unnatural transitions (common in AI text)
38
+ - Overly formal or generic tone (common in AI text)
39
+ - Creative, varied, or contextually nuanced patterns (common in human text)
40
+ - Coherence, emotional depth, and specific details (common in human text)
41
+
42
+ Analyze the following text and provide a JSON object with:
43
+ - 'ai_probability': a float (0 to 1) indicating the likelihood the text is AI-generated
44
+ - 'classification': a string, either 'AI-generated' or 'Human-written'
45
+ - 'reasons': a list of strings explaining the key factors influencing your decision
46
+
47
+ Use clear and concise reasoning, and include at least 2-3 specific observations about the text.
48
+
49
  Text: {text}
50
  """
51
  try:
 
58
  return result
59
  except Exception as e:
60
  print(f"Error in Ollama analysis: {e}")
61
+ return {
62
+ "ai_probability": 0.5,
63
+ "classification": "Unknown",
64
+ "reasons": ["Error in model analysis; unable to determine classification."]
65
+ }
66
 
67
  def classify_text(text: str) -> str:
68
+ """Classify text as AI or human-written and format output with reasons."""
69
  if not text or not text.strip():
70
+ return "❌ Error: No text provided."
71
+
72
  features = extract_features(text)
73
  ollama_result = analyze_text_with_ollama(text)
74
 
75
+ # Adjust AI probability based on linguistic features
76
  ai_score = ollama_result["ai_probability"]
77
  if features["word_diversity"] < 0.3: # Low diversity often indicates AI
78
  ai_score += 0.1
 
84
  # Cap the score between 0 and 1
85
  ai_score = min(max(ai_score, 0.0), 1.0)
86
 
87
+ # Override classification if adjusted score changes the outcome
88
+ classification = "AI-generated" if ai_score > 0.5 else "Human-written"
89
+
90
+ # Format output with sections and emojis
91
+ output = f"✅ **Classification**: {classification}\n\n"
92
+ output += f"📊 **AI Probability**: {ai_score:.2f}\n\n"
93
+ output += "❓ **Reasons**:\n"
94
+ for reason in ollama_result["reasons"]:
95
+ output += f"- {reason}\n"
96
+
97
+ # Add feature-based insights
98
+ output += "\n🔍 **Linguistic Features**:\n"
99
+ output += f"- Average Sentence Length: {features['avg_sentence_length']:.2f} words\n"
100
+ output += f"- Word Diversity: {features['word_diversity']:.2f} (unique words / total words)\n"
101
+ output += f"- Punctuation Ratio: {features['punctuation_ratio']:.4f} (punctuation / total characters)"
102
+
103
+ return output
104
 
105
  def main():
106
  """Launch Gradio interface for text analysis."""
107
  iface = gr.Interface(
108
  fn=classify_text,
109
  inputs=gr.Textbox(lines=10, placeholder="Enter your text here...", label="Input Text"),
110
+ outputs=gr.Markdown(label="Analysis Result"),
111
  title="AI vs Human Text Classifier",
112
+ description="Enter text to determine if it's likely AI-generated or human-written using Llama 3.1 8B and linguistic features. Results include classification, probability, and reasons."
113
  )
114
  iface.launch(server_name="0.0.0.0", server_port=7860)
115