hashirlodhi commited on
Commit
8e4afbb
·
verified ·
1 Parent(s): 8cedb00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -85
app.py CHANGED
@@ -1,118 +1,83 @@
1
  import os
2
  import gradio as gr
3
  import google.generativeai as genai
4
- from html import escape
5
 
6
- # Configure the Gemini API
7
  GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
8
  if not GOOGLE_API_KEY:
9
- raise ValueError("Please set your GOOGLE_API_KEY in the Hugging Face Space settings.")
10
 
11
  genai.configure(api_key=GOOGLE_API_KEY)
12
 
13
- # Use Gemini 1.5 Pro for better reasoning capabilities
14
- model = genai.GenerativeModel('gemini-1.5-pro')
15
 
16
  def classify_text(text):
17
  if not text.strip():
18
- return "Error: Please enter some text to analyze."
19
 
 
20
  prompt = f"""
21
- Analyze this text to determine if it's AI-generated or human-written. Provide:
22
- 1. Probability percentages (0-100%)
23
- 2. Key characteristics that indicate AI/human origin
24
- 3. Line-by-line analysis of suspicious patterns
25
 
26
- Text: "{text}"
 
 
 
 
27
 
28
- Respond in this EXACT format:
29
- AI Probability: [X]%
30
- Human Probability: [Y]%
31
- Key Characteristics: [bullet points]
32
- Line Analysis: [numbered lines with AI/human indicators]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  """
34
 
35
  try:
36
  response = model.generate_content(prompt)
 
37
  result = response.text.strip()
38
-
39
- # Parse the response
40
- ai_prob = "N/A"
41
- human_prob = "N/A"
42
- characteristics = []
43
- line_analysis = []
44
-
45
- for line in result.split('\n'):
46
- if line.startswith("AI Probability:"):
47
- ai_prob = line.split(':')[1].strip()
48
- elif line.startswith("Human Probability:"):
49
- human_prob = line.split(':')[1].strip()
50
- elif line.startswith("Key Characteristics:"):
51
- characteristics = [l.strip() for l in result.split('Key Characteristics:')[1].split('Line Analysis:')[0].split('- ')[1:]]
52
- elif line.startswith("Line Analysis:"):
53
- line_analysis = [l.strip() for l in result.split('Line Analysis:')[1].split('\n') if l.strip()]
54
-
55
- # Create colored HTML output
56
- html_output = f"""
57
- <div style="font-family: sans-serif; max-width: 800px;">
58
- <div style="display: flex; margin-bottom: 20px;">
59
- <div style="background-color: #ff6b6b; color: white; padding: 10px; width: {ai_prob};">AI: {ai_prob}</div>
60
- <div style="background-color: #51cf66; color: white; padding: 10px; width: {human_prob};">Human: {human_prob}</div>
61
- </div>
62
-
63
- <h3>Key Characteristics:</h3>
64
- <ul>
65
- {''.join([f'<li>{escape(c)}</li>' for c in characteristics])}
66
- </ul>
67
-
68
- <h3>Line-by-line Analysis:</h3>
69
- <div style="border: 1px solid #ddd; padding: 10px; border-radius: 5px;">
70
- """
71
-
72
- for line in line_analysis:
73
- if "AI indicator" in line.lower():
74
- html_output += f'<div style="background-color: #ffebee; padding: 5px; margin: 2px; border-left: 4px solid #ff6b6b;">{escape(line)}</div>'
75
- else:
76
- html_output += f'<div style="background-color: #ebfbee; padding: 5px; margin: 2px; border-left: 4px solid #51cf66;">{escape(line)}</div>'
77
-
78
- html_output += """
79
- </div>
80
- </div>
81
- """
82
-
83
- return html_output
84
-
85
  except Exception as e:
86
- return f"Error: {str(e)}"
87
-
88
- # Custom CSS for better appearance
89
- css = """
90
- .feedback textarea {font-size: 16px !important;}
91
- .prob-bar {height: 30px; display: flex; margin-bottom: 20px;}
92
- .ai-bar {background-color: #ff6b6b; color: white; display: flex; align-items: center; justify-content: center;}
93
- .human-bar {background-color: #51cf66; color: white; display: flex; align-items: center; justify-content: center;}
94
- .analysis-box {border: 1px solid #ddd; padding: 15px; border-radius: 8px; margin-top: 15px;}
95
- .ai-line {background-color: #ffebee; padding: 8px; margin: 5px 0; border-left: 4px solid #ff6b6b;}
96
- .human-line {background-color: #ebfbee; padding: 8px; margin: 5px 0; border-left: 4px solid #51cf66;}
97
- """
98
 
 
99
  examples = [
100
- "The cat sat on the mat, purring contentedly as sunlight streamed through the window.",
101
  "Large language models utilize transformer architectures to process sequential data efficiently.",
102
- "I totally forgot my umbrella and got soaked in the sudden downpour - typical for my luck!",
103
- "The implementation of quantum computing algorithms requires consideration of qubit coherence times."
104
  ]
105
 
106
  iface = gr.Interface(
107
  fn=classify_text,
108
- inputs=gr.Textbox(lines=5, placeholder="Paste text here to analyze...", label="Text Input"),
109
- outputs=gr.HTML(label="Analysis Results"),
110
- title="<span style='color: #333'>🔍 AI vs Human Text Analyzer</span>",
111
- description="""Analyze text to detect AI-generated content with visual probability indicators and line-by-line analysis.
112
- <br>Green = Human-like | Red = AI-like""",
113
- examples=examples,
114
- css=css
115
  )
116
 
 
117
  if __name__ == "__main__":
118
  iface.launch()
 
1
  import os
2
  import gradio as gr
3
  import google.generativeai as genai
 
4
 
5
+ # Configure the Gemini API with environment variable
6
  GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
7
  if not GOOGLE_API_KEY:
8
+ raise ValueError("GOOGLE_API_KEY environment variable not set. Please configure it in the Hugging Face Space settings.")
9
 
10
  genai.configure(api_key=GOOGLE_API_KEY)
11
 
12
+ # Use Gemini 1.5 Flash model
13
+ model = genai.GenerativeModel('gemini-1.5-flash-latest')
14
 
15
  def classify_text(text):
16
  if not text.strip():
17
+ return "Error: Please enter a non-empty text."
18
 
19
+ # More detailed and structured prompt
20
  prompt = f"""
21
+ Analyze the following text carefully and determine whether it was likely written by a human or generated by AI.
22
+ Consider these factors in your analysis:
 
 
23
 
24
+ 1. **Perplexity** - Human writing tends to have more unpredictable word choices
25
+ 2. **Burstiness** - Human writing shows more variation in sentence structure and length
26
+ 3. **Personal experience** - Humans often include subjective experiences or emotions
27
+ 4. **Imperfections** - Human writing may contain minor errors or informal expressions
28
+ 5. **Technical precision** - AI writing often has more technical accuracy but less personality
29
 
30
+ Provide your response in this exact format:
31
+
32
+ Classification: [AI-written/Human-written]
33
+ Confidence: [Low/Medium/High/Very High]
34
+ Reason: [Detailed explanation based on the analysis factors]
35
+
36
+ Examples of good analysis:
37
+
38
+ Text: "The utilization of neural networks facilitates the optimization of machine learning algorithms."
39
+ Classification: AI-written
40
+ Confidence: High
41
+ Reason: The text uses highly technical language with perfect grammar and focuses on algorithmic processes, which is characteristic of AI-generated content.
42
+
43
+ Text: "I was walking my dog when suddenly it started raining - we got soaked but had a good laugh about it!"
44
+ Classification: Human-written
45
+ Confidence: Very High
46
+ Reason: The text includes personal experience, emotional content ("good laugh"), and a casual narrative style with minor imperfections ("it started raining - we got") that are typical of human writing.
47
+
48
+ Now analyze this text:
49
+
50
+ "{text}"
51
  """
52
 
53
  try:
54
  response = model.generate_content(prompt)
55
+ # Simple post-processing to ensure consistent formatting
56
  result = response.text.strip()
57
+ if "Classification:" not in result:
58
+ return "Error: Unexpected response format from the model. Please try again."
59
+ return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  except Exception as e:
61
+ return f"Error: {str(e)}\nTip: Ensure your API key is valid at https://aistudio.google.com/"
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ # Define Gradio interface with more examples
64
  examples = [
65
+ "The cat sat on the mat, purring contentedly as the sun streamed through the window.",
66
  "Large language models utilize transformer architectures to process sequential data efficiently.",
67
+ "I totally forgot my umbrella today and got drenched in the sudden downpour - classic Monday!",
68
+ "The implementation of quantum computing algorithms requires careful consideration of qubit coherence times."
69
  ]
70
 
71
  iface = gr.Interface(
72
  fn=classify_text,
73
+ inputs=gr.Textbox(lines=5, placeholder="Enter text to classify...", label="Text Input"),
74
+ outputs=gr.Textbox(label="Analysis Result"),
75
+ title="Enhanced AI vs Human Text Classifier",
76
+ description="""A more sophisticated classifier that analyzes text for AI or human origin.
77
+ Considers linguistic patterns, style, and content. Set your GOOGLE_API_KEY in the Hugging Face Space settings.""",
78
+ examples=examples
 
79
  )
80
 
81
+ # Launch the interface
82
  if __name__ == "__main__":
83
  iface.launch()