Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,12 +3,12 @@ import requests
|
|
| 3 |
import gradio as gr
|
| 4 |
from typing import Dict
|
| 5 |
from crewai import Agent, Task, Crew
|
| 6 |
-
from
|
| 7 |
|
| 8 |
# Load OpenRouter API key
|
| 9 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 10 |
if not OPENROUTER_API_KEY:
|
| 11 |
-
raise
|
| 12 |
|
| 13 |
# Constants
|
| 14 |
API_URL = "https://openrouter.ai/api/v1/chat/completions"
|
|
@@ -20,79 +20,61 @@ class AICrewClassifier:
|
|
| 20 |
self.crew = Crew(agents=self.agents, verbose=2)
|
| 21 |
|
| 22 |
def _create_agents(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
return [
|
| 24 |
-
Agent(
|
| 25 |
-
|
| 26 |
-
goal="Analyze grammatical structures and syntax patterns",
|
| 27 |
-
backstory="Expert in detecting AI-generated linguistic patterns",
|
| 28 |
-
verbose=True
|
| 29 |
-
),
|
| 30 |
-
Agent(
|
| 31 |
-
role="Emotional Analyst",
|
| 32 |
-
goal="Evaluate emotional depth and authenticity",
|
| 33 |
-
backstory="Specializes in identifying genuine human emotional expression",
|
| 34 |
-
verbose=True
|
| 35 |
-
),
|
| 36 |
-
Agent(
|
| 37 |
-
role="Context Analyst",
|
| 38 |
-
goal="Examine logical flow and coherence",
|
| 39 |
-
backstory="Trained to spot AI-generated discontinuities in narratives",
|
| 40 |
-
verbose=True
|
| 41 |
-
),
|
| 42 |
-
Agent(
|
| 43 |
-
role="Technical Analyst",
|
| 44 |
-
goal="Analyze technical terminology usage",
|
| 45 |
-
backstory="Expert in detecting over-formalized AI technical language",
|
| 46 |
-
verbose=True
|
| 47 |
-
),
|
| 48 |
-
Agent(
|
| 49 |
-
role="Style Analyst",
|
| 50 |
-
goal="Examine writing style characteristics",
|
| 51 |
-
backstory="Specialist in identifying micro-level writing patterns",
|
| 52 |
-
verbose=True
|
| 53 |
-
)
|
| 54 |
]
|
| 55 |
|
| 56 |
-
def
|
| 57 |
if not text.strip():
|
| 58 |
-
|
|
|
|
| 59 |
|
| 60 |
-
tasks = [
|
| 61 |
Task(
|
| 62 |
-
description=f"
|
| 63 |
-
|
| 64 |
-
Provide:
|
| 65 |
-
1. Verdict: [AI|Human]
|
| 66 |
-
2. Confidence: [High|Medium|Low]
|
| 67 |
-
3. Key Evidence""",
|
| 68 |
agent=agent,
|
| 69 |
-
expected_output="
|
| 70 |
-
)
|
|
|
|
| 71 |
]
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
def _generate_summary(self, analysis: str) -> str:
|
| 86 |
-
prompt =
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
- [Reason 1]
|
| 94 |
-
- [Reason 2]"""
|
| 95 |
-
|
| 96 |
return self._query_llm(prompt)
|
| 97 |
|
| 98 |
def _query_llm(self, prompt: str) -> str:
|
|
@@ -104,53 +86,35 @@ class AICrewClassifier:
|
|
| 104 |
"model": MODEL_NAME,
|
| 105 |
"messages": [{"role": "user", "content": prompt}]
|
| 106 |
}
|
| 107 |
-
|
| 108 |
try:
|
| 109 |
-
response = requests.post(API_URL, headers=headers, json=payload)
|
| 110 |
response.raise_for_status()
|
| 111 |
-
return response.json()["choices"][0]["message"]["content"]
|
| 112 |
except Exception as e:
|
| 113 |
-
return f"
|
| 114 |
|
| 115 |
-
|
|
|
|
| 116 |
classifier = AICrewClassifier()
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
if "error" in result:
|
| 120 |
-
return result["error"]
|
| 121 |
-
|
| 122 |
-
output = [
|
| 123 |
-
"🔍 Multi-Agent Analysis Results",
|
| 124 |
-
"=============================",
|
| 125 |
-
result["analysis"],
|
| 126 |
-
"\n📋 Final Classification",
|
| 127 |
-
"=====================",
|
| 128 |
-
result["summary"]
|
| 129 |
-
]
|
| 130 |
-
|
| 131 |
-
return "\n".join(output)
|
| 132 |
|
| 133 |
-
# Gradio Interface
|
| 134 |
iface = gr.Interface(
|
| 135 |
-
fn=
|
| 136 |
inputs=gr.Textbox(
|
| 137 |
-
lines=
|
| 138 |
-
placeholder="Paste
|
| 139 |
-
label="
|
| 140 |
),
|
| 141 |
outputs=gr.Textbox(
|
| 142 |
-
label="Analysis
|
| 143 |
show_copy_button=True
|
| 144 |
),
|
| 145 |
-
title="🤖 AI vs Human Text Classifier (
|
| 146 |
-
description="
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
["My grandmother's apple pie always reminds me of childhood summers."]
|
| 150 |
-
],
|
| 151 |
-
allow_flagging="never",
|
| 152 |
-
theme="soft"
|
| 153 |
)
|
| 154 |
|
| 155 |
if __name__ == "__main__":
|
| 156 |
-
iface.launch()
|
|
|
|
| 3 |
import gradio as gr
|
| 4 |
from typing import Dict
|
| 5 |
from crewai import Agent, Task, Crew
|
| 6 |
+
from datetime import datetime
|
| 7 |
|
| 8 |
# Load OpenRouter API key
|
| 9 |
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 10 |
if not OPENROUTER_API_KEY:
|
| 11 |
+
raise EnvironmentError("Missing OPENROUTER_API_KEY environment variable.")
|
| 12 |
|
| 13 |
# Constants
|
| 14 |
API_URL = "https://openrouter.ai/api/v1/chat/completions"
|
|
|
|
| 20 |
self.crew = Crew(agents=self.agents, verbose=2)
|
| 21 |
|
| 22 |
def _create_agents(self):
|
| 23 |
+
roles = [
|
| 24 |
+
("Linguistic Analyst", "Analyze grammar, syntax, and structure", "Expert in AI-style linguistic patterns"),
|
| 25 |
+
("Emotional Analyst", "Evaluate emotional tone and authenticity", "Specialist in human emotional cues"),
|
| 26 |
+
("Context Analyst", "Check logical coherence and consistency", "Trained to detect AI-like discontinuity"),
|
| 27 |
+
("Technical Analyst", "Review use of technical terminology", "Expert in formal and structured language"),
|
| 28 |
+
("Style Analyst", "Analyze stylistic elements of writing", "Identifies micro-level stylistic patterns")
|
| 29 |
+
]
|
| 30 |
return [
|
| 31 |
+
Agent(role=role, goal=goal, backstory=backstory, verbose=True)
|
| 32 |
+
for role, goal, backstory in roles
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
]
|
| 34 |
|
| 35 |
+
def analyze_text_streaming(self, text: str):
|
| 36 |
if not text.strip():
|
| 37 |
+
yield "❗ Please enter some valid text."
|
| 38 |
+
return
|
| 39 |
|
| 40 |
+
self.crew.tasks = [
|
| 41 |
Task(
|
| 42 |
+
description=f"Your role is {agent.role}. Analyze this text:\n\n{text}\n\n"
|
| 43 |
+
f"Give:\n1. Verdict: [AI|Human]\n2. Confidence: [High|Medium|Low]\n3. Key Evidence.",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
agent=agent,
|
| 45 |
+
expected_output="Verdict, confidence, and key evidence."
|
| 46 |
+
)
|
| 47 |
+
for agent in self.agents
|
| 48 |
]
|
| 49 |
|
| 50 |
+
results_combined = ""
|
| 51 |
+
for i, task in enumerate(self.crew.tasks):
|
| 52 |
+
yield f"⚙️ Processing Task {i + 1} of {len(self.crew.tasks)}: **{task.agent.role}**"
|
| 53 |
+
result = task.execute()
|
| 54 |
+
results_combined += f"\n🧩 **{task.agent.role}**:\n{result}\n"
|
| 55 |
+
yield f"✅ **{task.agent.role} completed**\n"
|
| 56 |
+
|
| 57 |
+
yield "🧠 All agents finished. Generating summary..."
|
| 58 |
+
summary = self._generate_summary(results_combined)
|
| 59 |
+
|
| 60 |
+
final_output = (
|
| 61 |
+
"🧠 **Multi-Agent Analysis Complete**\n"
|
| 62 |
+
"------------------------------\n"
|
| 63 |
+
f"{results_combined.strip()}\n\n"
|
| 64 |
+
"✅ **Final Classification Summary**\n"
|
| 65 |
+
"------------------------------\n"
|
| 66 |
+
f"{summary.strip()}"
|
| 67 |
+
)
|
| 68 |
+
yield final_output
|
| 69 |
|
| 70 |
def _generate_summary(self, analysis: str) -> str:
|
| 71 |
+
prompt = (
|
| 72 |
+
f"Based on the following multi-agent analysis:\n\n{analysis}\n\n"
|
| 73 |
+
"Summarize with:\n"
|
| 74 |
+
"Final Verdict: [AI-Written | Human-Written]\n"
|
| 75 |
+
"Confidence: [Percentage, e.g., 85%]\n"
|
| 76 |
+
"Key Reasons:\n- Reason 1\n- Reason 2"
|
| 77 |
+
)
|
|
|
|
|
|
|
|
|
|
| 78 |
return self._query_llm(prompt)
|
| 79 |
|
| 80 |
def _query_llm(self, prompt: str) -> str:
|
|
|
|
| 86 |
"model": MODEL_NAME,
|
| 87 |
"messages": [{"role": "user", "content": prompt}]
|
| 88 |
}
|
|
|
|
| 89 |
try:
|
| 90 |
+
response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
|
| 91 |
response.raise_for_status()
|
| 92 |
+
return response.json()["choices"][0]["message"]["content"].strip()
|
| 93 |
except Exception as e:
|
| 94 |
+
return f"❌ Error generating summary: {str(e)}"
|
| 95 |
|
| 96 |
+
# Live Chat Interface using Generator
|
| 97 |
+
def stream_analyzer(text):
|
| 98 |
classifier = AICrewClassifier()
|
| 99 |
+
yield from classifier.analyze_text_streaming(text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
# Gradio Streaming Interface
|
| 102 |
iface = gr.Interface(
|
| 103 |
+
fn=stream_analyzer,
|
| 104 |
inputs=gr.Textbox(
|
| 105 |
+
lines=6,
|
| 106 |
+
placeholder="Paste any paragraph or writing to analyze...",
|
| 107 |
+
label="Input Text"
|
| 108 |
),
|
| 109 |
outputs=gr.Textbox(
|
| 110 |
+
label="Live Agent Analysis Output",
|
| 111 |
show_copy_button=True
|
| 112 |
),
|
| 113 |
+
title="🤖 AI vs Human Text Classifier (Live Agent Feedback)",
|
| 114 |
+
description="👁️ Watch each CrewAI agent analyze the text in real time like n8n nodes executing. Summary verdict at the end.",
|
| 115 |
+
theme="soft",
|
| 116 |
+
allow_flagging="never"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
)
|
| 118 |
|
| 119 |
if __name__ == "__main__":
|
| 120 |
+
iface.launch()
|