Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,12 +6,12 @@ from langchain_huggingface import HuggingFaceEmbeddings
|
|
| 6 |
from langchain_core.documents import Document
|
| 7 |
|
| 8 |
# ==========================================
|
| 9 |
-
# 1. INITIALIZE
|
| 10 |
# ==========================================
|
| 11 |
-
print("Loading Embedding
|
| 12 |
embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 13 |
|
| 14 |
-
print("
|
| 15 |
chat_pipeline = pipeline(
|
| 16 |
"text-generation",
|
| 17 |
model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
|
|
@@ -19,88 +19,109 @@ chat_pipeline = pipeline(
|
|
| 19 |
torch_dtype=torch.float32
|
| 20 |
)
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
"
|
| 27 |
-
"Remote work: Data indicates remote workers are 13% more productive but face severe communication bottlenecks.",
|
| 28 |
-
"Electric Vehicles: EVs produce zero tailpipe emissions, but lithium battery mining has heavy environmental impacts.",
|
| 29 |
-
"Universal Basic Income: UBI trials show decreased poverty rates but raise concerns about labor market contraction."
|
| 30 |
]
|
| 31 |
-
documents = [Document(page_content=text) for text in
|
| 32 |
vector_store = FAISS.from_documents(documents, embedding_model)
|
| 33 |
|
|
|
|
| 34 |
# ==========================================
|
| 35 |
-
#
|
| 36 |
# ==========================================
|
| 37 |
-
def
|
| 38 |
if not user_input.strip():
|
| 39 |
-
return "β οΈ
|
| 40 |
-
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
-
if
|
| 44 |
retriever = vector_store.as_retriever(search_kwargs={"k": 1})
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
# Build Prompt using TinyLlama Token Format
|
| 49 |
-
system_headers = f"{custom_sys_prompt} {context}".strip()
|
| 50 |
-
prompt = f"<|system|>\n{system_headers}</s>\n<|user|>\n{user_input}</s>\n<|assistant|>\n"
|
| 51 |
-
|
| 52 |
try:
|
| 53 |
-
|
| 54 |
-
|
| 55 |
max_new_tokens=int(max_tokens),
|
| 56 |
-
do_sample=True,
|
| 57 |
-
temperature=float(temp),
|
| 58 |
top_p=float(top_p),
|
| 59 |
-
top_k=
|
|
|
|
| 60 |
)
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
# ==========================================
|
| 68 |
-
#
|
| 69 |
# ==========================================
|
| 70 |
with gr.Blocks() as demo:
|
| 71 |
|
| 72 |
-
#
|
| 73 |
with gr.Row():
|
| 74 |
-
with gr.Column(scale=
|
| 75 |
gr.Markdown("# π€ AI News Debate & Summary Agent Suite")
|
| 76 |
gr.Markdown(
|
| 77 |
"**About This Agent:** This framework processes user statements and news artifacts "
|
| 78 |
"to provide dual NLP functions: an adversarial debate environment using real-time "
|
| 79 |
"vectorized context verification, and an automated complex-news generalization engine."
|
| 80 |
)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
with gr.Row():
|
| 93 |
-
|
|
|
|
| 94 |
with gr.Column(scale=1):
|
| 95 |
gr.Markdown("### π οΈ Agent Workspaces")
|
| 96 |
|
| 97 |
-
with gr.Tabs() as
|
| 98 |
-
|
|
|
|
| 99 |
with gr.TabItem("ποΈ News Debate Agent", id=0):
|
| 100 |
gr.Markdown("*State a topic and your stance. The agent will pull factual context, debate you, and score your logic.*")
|
| 101 |
-
|
| 102 |
label="Your Stance",
|
| 103 |
-
placeholder="
|
| 104 |
)
|
| 105 |
gr.Examples(
|
| 106 |
examples=[
|
|
@@ -108,67 +129,65 @@ with gr.Blocks() as demo:
|
|
| 108 |
["Electric vehicles are the only way to save the environment."],
|
| 109 |
["Universal Basic Income will just make people lazy."]
|
| 110 |
],
|
| 111 |
-
inputs=
|
| 112 |
)
|
| 113 |
-
|
| 114 |
|
| 115 |
-
#
|
| 116 |
with gr.TabItem("π° Snippet Generalizer", id=1):
|
| 117 |
gr.Markdown("*Paste complex, jargon-heavy news columns here to output plain-English, executive summaries.*")
|
| 118 |
-
|
| 119 |
label="Complex News Snippet",
|
| 120 |
-
lines=
|
| 121 |
-
placeholder="Paste
|
| 122 |
)
|
| 123 |
gr.Examples(
|
| 124 |
examples=[
|
| 125 |
-
["Despite aggressive macroeconomic headwinds and structural quantitative tightening by central banking systems, retail index trends demonstrated non-linear elasticity during
|
| 126 |
-
["The ecosystem validation vectors indicate substantial degradation in sub-surface lithospheric layers owing to chemical
|
| 127 |
],
|
| 128 |
-
inputs=
|
| 129 |
)
|
| 130 |
-
|
| 131 |
|
| 132 |
-
|
| 133 |
-
gr.HTML("<div style='height: 15px;'></div>")
|
| 134 |
|
| 135 |
-
#
|
| 136 |
with gr.Accordion("βοΈ Advanced Agent Parameter Configurations", open=False):
|
| 137 |
-
|
| 138 |
-
label="System Prompt Context Injection",
|
| 139 |
value=(
|
| 140 |
-
"You are a
|
| 141 |
-
"If
|
| 142 |
-
"If
|
| 143 |
),
|
| 144 |
-
lines=
|
| 145 |
)
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
|
| 150 |
-
#
|
| 151 |
with gr.Column(scale=1):
|
| 152 |
gr.Markdown("### π₯οΈ Active Output Stream")
|
| 153 |
-
|
|
|
|
|
|
|
| 154 |
|
| 155 |
# ==========================================
|
| 156 |
-
#
|
| 157 |
# ==========================================
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
outputs=output_display
|
| 163 |
)
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
outputs=output_display
|
| 170 |
)
|
| 171 |
|
| 172 |
if __name__ == "__main__":
|
| 173 |
-
# Theme configuration moved to launch parameter to fully satisfy Gradio 6.0 specifications
|
| 174 |
demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft())
|
|
|
|
| 6 |
from langchain_core.documents import Document
|
| 7 |
|
| 8 |
# ==========================================
|
| 9 |
+
# 1. INITIALIZE MODELS & VECTOR BASE
|
| 10 |
# ==========================================
|
| 11 |
+
print("Loading Embedding Engine...")
|
| 12 |
embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 13 |
|
| 14 |
+
print("Initializing Local TinyLlama Core on CPU...")
|
| 15 |
chat_pipeline = pipeline(
|
| 16 |
"text-generation",
|
| 17 |
model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
|
|
|
|
| 19 |
torch_dtype=torch.float32
|
| 20 |
)
|
| 21 |
|
| 22 |
+
# Fact-checking context store
|
| 23 |
+
mock_news_db = [
|
| 24 |
+
"AI and Automation: Global studies confirm that while AI will replace 85 million routine operational jobs by late 2026, it simultaneously offsets this by engineering 97 million technical roles.",
|
| 25 |
+
"EV Industrial Lifecycle: Electric Vehicles emit zero greenhouse operational gases, but lithium-ion battery extraction increases heavy localized ecosystem toxicity by 42%.",
|
| 26 |
+
"Universal Basic Income: Comprehensive economic trials indicate UBI successfully lowers base poverty indexes but sparks minor macro-inflationary pressures across basic retail commodities."
|
|
|
|
|
|
|
|
|
|
| 27 |
]
|
| 28 |
+
documents = [Document(page_content=text) for text in mock_news_db]
|
| 29 |
vector_store = FAISS.from_documents(documents, embedding_model)
|
| 30 |
|
| 31 |
+
|
| 32 |
# ==========================================
|
| 33 |
+
# 2. OPTIMIZED INFERENCE CONTROLLER
|
| 34 |
# ==========================================
|
| 35 |
+
def execution_engine(workspace_type, user_input, system_injection, max_tokens, temp, top_p):
|
| 36 |
if not user_input.strip():
|
| 37 |
+
return "β οΈ **System Input Error:** Workspace field cannot be processed empty."
|
| 38 |
+
|
| 39 |
+
# RAG Hook for Debate Mode
|
| 40 |
+
context_data = ""
|
| 41 |
+
if workspace_type == "debate":
|
| 42 |
retriever = vector_store.as_retriever(search_kwargs={"k": 1})
|
| 43 |
+
matched_docs = retriever.invoke(user_input)
|
| 44 |
+
if matched_docs:
|
| 45 |
+
context_data = f"\nUse this background context for verification: {matched_docs[0].page_content}"
|
| 46 |
+
|
| 47 |
+
# Build clear structural rules to prevent sentence truncation
|
| 48 |
+
tailored_instructions = (
|
| 49 |
+
f"{system_injection} {context_data}\n"
|
| 50 |
+
"CRITICAL: Keep your response short, concise, and structured. "
|
| 51 |
+
"Ensure your final sentence is completely finished. Do not cut off mid-sentence."
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# Format explicitly into TinyLlama prompt structures
|
| 55 |
+
formatted_prompt = f"<|system|>\n{tailored_instructions}</s>\n<|user|>\n{user_input}</s>\n<|assistant|>\n"
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
try:
|
| 58 |
+
raw_output = chat_pipeline(
|
| 59 |
+
formatted_prompt,
|
| 60 |
max_new_tokens=int(max_tokens),
|
| 61 |
+
do_sample=True,
|
| 62 |
+
temperature=float(temp),
|
| 63 |
top_p=float(top_p),
|
| 64 |
+
top_k=40,
|
| 65 |
+
repetition_penalty=1.2 # Prevents model looping or stalling on CPU
|
| 66 |
)
|
| 67 |
+
|
| 68 |
+
processed_text = raw_output[0]["generated_text"].split("<|assistant|>\n")[-1].strip()
|
| 69 |
+
|
| 70 |
+
# Clean up any potential dangling uncompleted tail sentence due to token limits
|
| 71 |
+
if processed_text and processed_text[-1] not in [".", "!", "?", '"']:
|
| 72 |
+
last_punctuation = max(processed_text.rfind("."), processed_text.rfind("!"), processed_text.rfind("?"))
|
| 73 |
+
if last_punctuation != -1:
|
| 74 |
+
processed_text = processed_text[:last_punctuation + 1]
|
| 75 |
+
|
| 76 |
+
return processed_text
|
| 77 |
+
|
| 78 |
+
except Exception as error:
|
| 79 |
+
return f"β **Pipeline Fault:** Execution timed out or memory overflow occurred. Details: {str(error)}"
|
| 80 |
+
|
| 81 |
|
| 82 |
# ==========================================
|
| 83 |
+
# 3. DASHBOARD WINDOW BUILDER (SCREENSHOT 583)
|
| 84 |
# ==========================================
|
| 85 |
with gr.Blocks() as demo:
|
| 86 |
|
| 87 |
+
# Top Banner Section
|
| 88 |
with gr.Row():
|
| 89 |
+
with gr.Column(scale=3):
|
| 90 |
gr.Markdown("# π€ AI News Debate & Summary Agent Suite")
|
| 91 |
gr.Markdown(
|
| 92 |
"**About This Agent:** This framework processes user statements and news artifacts "
|
| 93 |
"to provide dual NLP functions: an adversarial debate environment using real-time "
|
| 94 |
"vectorized context verification, and an automated complex-news generalization engine."
|
| 95 |
)
|
| 96 |
+
|
| 97 |
+
# Status Module Panel (Mirroring Right side of Screenshot 583)
|
| 98 |
+
with gr.Column(scale=1):
|
| 99 |
+
with gr.HighlightedText(value=[("ONLINE", "π’ NLP Match Engine Status")], show_label=False):
|
| 100 |
+
pass
|
| 101 |
+
gr.Markdown(
|
| 102 |
+
"πͺͺ **Agent Profile:** Similarity-Augmented Assistant \n"
|
| 103 |
+
"π¦ **Model Matrix:** TinyLlama-1.1B (Quantized Pipeline) \n"
|
| 104 |
+
"𧬠**Vectorization Engine:** Text FAISS Embedder \n"
|
| 105 |
+
"π» **Processing Hardware:** Base CPU Architecture"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
gr.HTML("<hr style='border: 0.5px solid #374151; margin: 15px 0;'/>")
|
| 109 |
+
|
| 110 |
+
# Lower Workspace Splitting Layout
|
| 111 |
with gr.Row():
|
| 112 |
+
|
| 113 |
+
# Left Panel Workspace
|
| 114 |
with gr.Column(scale=1):
|
| 115 |
gr.Markdown("### π οΈ Agent Workspaces")
|
| 116 |
|
| 117 |
+
with gr.Tabs() as active_workspace_tabs:
|
| 118 |
+
|
| 119 |
+
# Tab (i): Debate Module
|
| 120 |
with gr.TabItem("ποΈ News Debate Agent", id=0):
|
| 121 |
gr.Markdown("*State a topic and your stance. The agent will pull factual context, debate you, and score your logic.*")
|
| 122 |
+
debate_text_input = gr.Textbox(
|
| 123 |
label="Your Stance",
|
| 124 |
+
placeholder="Type your claim here..."
|
| 125 |
)
|
| 126 |
gr.Examples(
|
| 127 |
examples=[
|
|
|
|
| 129 |
["Electric vehicles are the only way to save the environment."],
|
| 130 |
["Universal Basic Income will just make people lazy."]
|
| 131 |
],
|
| 132 |
+
inputs=debate_text_input
|
| 133 |
)
|
| 134 |
+
run_debate_action = gr.Button("Deploy Counter-Argument & Score", variant="primary")
|
| 135 |
|
| 136 |
+
# Tab (ii): Text Simplification Module
|
| 137 |
with gr.TabItem("π° Snippet Generalizer", id=1):
|
| 138 |
gr.Markdown("*Paste complex, jargon-heavy news columns here to output plain-English, executive summaries.*")
|
| 139 |
+
simplify_text_input = gr.Textbox(
|
| 140 |
label="Complex News Snippet",
|
| 141 |
+
lines=4,
|
| 142 |
+
placeholder="Paste text block or official reports here..."
|
| 143 |
)
|
| 144 |
gr.Examples(
|
| 145 |
examples=[
|
| 146 |
+
["Despite aggressive macroeconomic headwinds and structural quantitative tightening by central banking systems, retail index trends demonstrated non-linear elasticity during fiscal evaluations."],
|
| 147 |
+
["The ecosystem validation vectors indicate substantial degradation in sub-surface lithospheric layers owing to chemical manufacturing runoffs, sparking compliance friction."]
|
| 148 |
],
|
| 149 |
+
inputs=simplify_text_input
|
| 150 |
)
|
| 151 |
+
run_simplifier_action = gr.Button("Generalize for Easy Understanding", variant="primary")
|
| 152 |
|
| 153 |
+
gr.HTML("<div style='margin-bottom: 20px;'></div>")
|
|
|
|
| 154 |
|
| 155 |
+
# Param Configuration Module
|
| 156 |
with gr.Accordion("βοΈ Advanced Agent Parameter Configurations", open=False):
|
| 157 |
+
sys_prompt_template = gr.TextArea(
|
| 158 |
+
label="System Prompt Context Injection",
|
| 159 |
value=(
|
| 160 |
+
"You are a concise engineering assistant. "
|
| 161 |
+
"If processing a debate, provide a direct counter-argument under 3 sentences and end with a bolded 'Argument Logic Score: X/10'. "
|
| 162 |
+
"If simplifying, explain the point directly in clear bullet points under 50 words total."
|
| 163 |
),
|
| 164 |
+
lines=3
|
| 165 |
)
|
| 166 |
+
max_tokens_val = gr.Slider(minimum=64, maximum=300, value=160, step=16, label="Max new tokens")
|
| 167 |
+
temp_val = gr.Slider(minimum=0.1, maximum=1.0, value=0.3, step=0.05, label="Temperature")
|
| 168 |
+
top_p_val = gr.Slider(minimum=0.50, maximum=1.00, value=0.85, step=0.05, label="Top-p")
|
| 169 |
|
| 170 |
+
# Right Panel Output Monitor
|
| 171 |
with gr.Column(scale=1):
|
| 172 |
gr.Markdown("### π₯οΈ Active Output Stream")
|
| 173 |
+
active_output_panel = gr.Markdown(
|
| 174 |
+
value="*System ready. Select a workspace on the left panel and click deploy to review parsed generation stream.*"
|
| 175 |
+
)
|
| 176 |
|
| 177 |
# ==========================================
|
| 178 |
+
# 4. EVENT MAP TRANSLATORS
|
| 179 |
# ==========================================
|
| 180 |
+
run_debate_action.click(
|
| 181 |
+
fn=lambda user_in, sys_p, tokens, t, p: execution_engine("debate", user_in, sys_p, tokens, t, p),
|
| 182 |
+
inputs=[debate_text_input, sys_prompt_template, max_tokens_val, temp_val, top_p_val],
|
| 183 |
+
outputs=active_output_panel
|
|
|
|
| 184 |
)
|
| 185 |
|
| 186 |
+
run_simplifier_action.click(
|
| 187 |
+
fn=lambda user_in, sys_p, tokens, t, p: execution_engine("generalize", user_in, sys_p, tokens, t, p),
|
| 188 |
+
inputs=[simplify_text_input, sys_prompt_template, max_tokens_val, temp_val, top_p_val],
|
| 189 |
+
outputs=active_output_panel
|
|
|
|
| 190 |
)
|
| 191 |
|
| 192 |
if __name__ == "__main__":
|
|
|
|
| 193 |
demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft())
|