hashirlodhi commited on
Commit
8f66238
Β·
verified Β·
1 Parent(s): faee059

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -60
app.py CHANGED
@@ -1,68 +1,120 @@
1
- import os
2
- import requests
 
3
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- # Hugging Face Inference API settings
6
- API_URL = "https://api-inference.huggingface.co/models/qwen/Qwen1.5-72B-Chat"
7
- API_KEY = os.getenv("HF_API_KEY") # Set this in your Hugging Face Space secrets
8
-
9
- def classify_text(text):
10
- if not text.strip():
11
- return "Error: Please enter a non-empty text."
12
-
13
- prompt = f"""
14
- 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.
15
- 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.
16
-
17
- Analyze the following text and return the result in the exact format:
18
-
19
- Classification: [AI-written / Human-written]
20
- Reason: [Short but strong explanation β€” logic, tone, structure, etc.]
21
-
22
- Text: "{text}"
23
- Classification:
24
- Reason:
25
- """
26
-
27
- headers = {
28
- "Authorization": f"Bearer {API_KEY}",
29
- "Content-Type": "application/json"
30
- }
31
-
32
- payload = {
33
- "inputs": prompt,
34
- "parameters": {
35
- "max_new_tokens": 200,
36
- "temperature": 0.3
37
- }
38
- }
39
-
40
- try:
41
- response = requests.post(API_URL, headers=headers, json=payload)
42
- response.raise_for_status()
43
- result = response.json()
44
-
45
- # Handle the response format from Hugging Face API
46
- if isinstance(result, list) and len(result) > 0:
47
- if 'generated_text' in result[0]:
48
- return result[0]['generated_text'].strip()
49
- return result[0].get('text', str(result)).strip()
50
- return str(result)
51
- except Exception as e:
52
- return f"Error: {str(e)}\nTip: Make sure the API key is correct and the model is loaded."
 
 
 
 
 
 
 
 
 
 
53
 
54
  # Gradio interface
55
  iface = gr.Interface(
56
- fn=classify_text,
57
- inputs=gr.Textbox(lines=5, placeholder="Paste text to classify...", label="Text Input"),
58
- outputs=gr.Textbox(label="Classification Result"),
59
- title="πŸ€– AI vs Human Text Classifier (Qwen 72B)",
60
- description="""Detect if your text is AI-generated or Human-written using Qwen 72B model via Hugging Face API.
61
-
62
- Note: First request may take 10-20 seconds while the model loads.""",
63
- allow_flagging="never"
64
  )
65
 
66
- # Launch the Gradio app
 
 
67
  if __name__ == "__main__":
68
- iface.launch()
 
1
+ # AI_Text_Analyzer_Gradio.py
2
+
3
+ # Import required libraries
4
  import gradio as gr
5
+ from crewai import Agent, Task, Crew
6
+ from transformers import pipeline
7
+ import numpy as np
8
+
9
+ # Initialize Hugging Face classifier for AI text detection
10
+ classifier = pipeline("text-classification", model="roberta-base", tokenizer="roberta-base")
11
+
12
+ # Placeholder for LLM (replace with Hugging Face model, e.g., Llama-3.1-8B)
13
+ # Note: Requires Hugging Face API token for gated models
14
+ llm = None # Configure with, e.g., HuggingFaceLLM(model='meta-llama/Llama-3.1-8B')
15
+
16
+ # πŸ“ Linguistic Pattern Analyzer
17
+ pattern_analyzer = Agent(
18
+ role='Linguistic Pattern Analyzer',
19
+ goal='Analyze linguistic patterns (tone, word choice, sentence structure) to identify human or AI authorship',
20
+ backstory='You are an expert in NLP, adept at spotting patterns like repetitive phrasing (AI) or emotional nuance (human).',
21
+ llm=llm
22
+ )
23
+
24
+ # πŸ” Coherence and Context Evaluator
25
+ coherence_evaluator = Agent(
26
+ role='Coherence and Context Evaluator',
27
+ goal='Assess logical flow, contextual consistency, and coherence for human or AI writing traits',
28
+ backstory='You excel at detecting logical inconsistencies (AI) or narrative depth (human) in text.',
29
+ llm=llm
30
+ )
31
+
32
+ # 🎨 Style Analyzer
33
+ style_analyzer = Agent(
34
+ role='Style Analyzer',
35
+ goal='Evaluate stylistic elements like creativity, emotional depth, and uniqueness',
36
+ backstory='You specialize in identifying creative flair or formulaic patterns in writing styles.',
37
+ llm=llm
38
+ )
39
+
40
+ # 🧠 Final Verdict Compiler
41
+ verdict_compiler = Agent(
42
+ role='Verdict Compiler',
43
+ goal='Synthesize analyses and classifier output for a final verdict with a confidence score',
44
+ backstory='You are a meticulous analyst, combining multiple perspectives and model predictions for accurate verdicts.',
45
+ llm=llm
46
+ )
47
 
48
+ def analyze_text(input_text):
49
+ # Input validation
50
+ if not input_text or len(input_text.strip()) < 10:
51
+ return "Error: Please provide a text with at least 10 characters."
52
+
53
+ # Run pre-trained classifier
54
+ classifier_result = classifier(input_text, truncation=True, max_length=512)
55
+ classifier_score = classifier_result[0]['score'] if classifier_result[0]['label'] == 'POSITIVE' else 1 - classifier_result[0]['score']
56
+ classifier_verdict = 'AI' if classifier_result[0]['label'] == 'POSITIVE' else 'Human'
57
+
58
+ # Task 1 - Linguistic Pattern Analysis
59
+ task1 = Task(
60
+ description=f'Analyze the text for linguistic patterns (e.g., tone, word choice, sentence structure): "{input_text}". Identify specific traits (e.g., repetitive phrasing, emotional nuance) indicating human or AI authorship.',
61
+ expected_output='A 2-3 sentence analysis of linguistic patterns with evidence for human or AI authorship.',
62
+ agent=pattern_analyzer
63
+ )
64
+
65
+ # Task 2 - Coherence and Context Evaluation
66
+ task2 = Task(
67
+ description=f'Evaluate the logical flow, contextual consistency, and coherence of: "{input_text}". Highlight traits like logical gaps (AI) or narrative depth (human).',
68
+ expected_output='A 2-3 sentence evaluation of coherence and context, indicating human or AI authorship.',
69
+ agent=coherence_evaluator,
70
+ depends_on=[task1]
71
+ )
72
+
73
+ # Task 3 - Style Analysis
74
+ task3 = Task(
75
+ description=f'Analyze the stylistic elements (e.g., creativity, emotional depth, uniqueness) of: "{input_text}". Note signs of formulaic patterns (AI) or creative flair (human).',
76
+ expected_output='A 2-3 sentence analysis of style, indicating human or AI authorship.',
77
+ agent=style_analyzer,
78
+ depends_on=[task1]
79
+ )
80
+
81
+ # Task 4 - Final Verdict Compilation
82
+ task4 = Task(
83
+ description=f'Combine linguistic, coherence, style analyses, and classifier score ({classifier_verdict}, {classifier_score:.2%}) to provide a final verdict on whether the text is human or AI-written. Assign a confidence score (0-100%) based on weighted evidence (classifier: 40%, linguistic: 20%, coherence: 20%, style: 20%).',
84
+ expected_output='A 5-6 line summary with the final verdict, confidence score, and key reasons.',
85
+ agent=verdict_compiler,
86
+ depends_on=[task1, task2, task3]
87
+ )
88
+
89
+ # Create and run the Crew
90
+ crew = Crew(
91
+ agents=[pattern_analyzer, coherence_evaluator, style_analyzer, verdict_compiler],
92
+ tasks=[task1, task2, task3, task4]
93
+ )
94
+
95
+ # Execute tasks
96
+ result = crew.kickoff()
97
+
98
+ # Format output for Gradio
99
+ output = f"🏁 AI Text Analysis Result:\n\n{result}\n\n"
100
+ output += f"Classifier Prediction: {classifier_verdict} ({classifier_score:.2%})\n"
101
+ output += "\n🌟 Try It Again!\n- Test with different texts (e.g., personal notes, blog posts, AI-generated content).\n"
102
+ output += "- Compare short vs. long texts or formal vs. informal tones.\n"
103
+ output += "- See how the verdict and confidence score change!"
104
+
105
+ return output
106
 
107
  # Gradio interface
108
  iface = gr.Interface(
109
+ fn=analyze_text,
110
+ inputs=gr.Textbox(lines=5, placeholder="Enter the text to analyze here..."),
111
+ outputs=gr.Textbox(),
112
+ title="AI Text Analyzer",
113
+ description="Enter a text sample to determine if it was likely written by a human or an AI. The system uses linguistic, coherence, and style analysis, combined with a pre-trained classifier, for accurate results."
 
 
 
114
  )
115
 
116
+ # Launch the interface (comment out for Hugging Face Spaces; Gradio handles this automatically)
117
+ # iface.launch()
118
+
119
  if __name__ == "__main__":
120
+ print("This script is designed to run on Hugging Face Spaces with Gradio. Deploy it there or uncomment iface.launch() for local testing.")