VectorV17 commited on
Commit
8f9986a
Β·
verified Β·
1 Parent(s): dde551a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -90
app.py CHANGED
@@ -6,12 +6,12 @@ from langchain_huggingface import HuggingFaceEmbeddings
6
  from langchain_core.documents import Document
7
 
8
  # ==========================================
9
- # 1. INITIALIZE MODERN CPU PIPELINES
10
  # ==========================================
11
- print("Loading Embedding Model...")
12
  embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
13
 
14
- print("Loading LLM (TinyLlama-1.1B) on CPU...")
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
- # 2. BUILD LOCAL CONTEXT (FAISS)
24
- # ==========================================
25
- mock_news_data = [
26
- "AI taking over jobs: Studies show AI will displace 85 million jobs, but create 97 million new ones by 2026.",
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 mock_news_data]
32
  vector_store = FAISS.from_documents(documents, embedding_model)
33
 
 
34
  # ==========================================
35
- # 3. WORKSPACE CORE COGNITION LOGIC
36
  # ==========================================
37
- def run_agent_task(task_type, user_input, custom_sys_prompt, max_tokens, temp, top_p):
38
  if not user_input.strip():
39
- return "⚠️ Please provide input text before running the agent."
40
-
41
- # Context Retrieval if it's a debate task
42
- context = ""
43
- if task_type == "debate":
44
  retriever = vector_store.as_retriever(search_kwargs={"k": 1})
45
- docs = retriever.invoke(user_input)
46
- context = f"\nUse this verified news context to formulate your argument: {docs[0].page_content}" if docs else ""
 
 
 
 
 
 
 
 
 
 
 
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
- outputs = chat_pipeline(
54
- prompt,
55
  max_new_tokens=int(max_tokens),
56
- do_sample=True,
57
- temperature=float(temp),
58
  top_p=float(top_p),
59
- top_k=50
 
60
  )
61
- # Parse output accurately
62
- generated_text = outputs[0]["generated_text"]
63
- return generated_text.split("<|assistant|>\n")[-1].strip()
64
- except Exception as e:
65
- return f"❌ Execution Error: {str(e)}"
 
 
 
 
 
 
 
 
 
66
 
67
  # ==========================================
68
- # 4. DASHBOARD INTERFACE DESIGN
69
  # ==========================================
70
  with gr.Blocks() as demo:
71
 
72
- # Header & About Banner (Inspired by Screenshot 573)
73
  with gr.Row():
74
- with gr.Column(scale=4):
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
- with gr.Column(scale=1, min_width=150):
82
- with gr.Group():
83
- gr.Markdown("### 🟒 NLP Match Engine Status")
84
- gr.Markdown(
85
- "πŸ€– **Agent Profile:** Similarity-Augmented Assistant\n\n"
86
- "πŸ“¦ **Model Matrix:** TinyLlama-1.1B (Quantized Inference Pipeline)\n\n"
87
- "🧬 **Vectorization Engine:** Text FAISS Embedding Retriever\n\n"
88
- "πŸ’» **Processing Hardware:** Base CPU Architecture"
89
- )
90
- gr.HTML("<hr style='border: 1px solid #e5e7eb; margin-bottom: 20px;'/>")
91
-
 
 
 
 
92
  with gr.Row():
93
- # LEFT-HAND COLUMN: Interactive Workspaces & Hyperparameters
 
94
  with gr.Column(scale=1):
95
  gr.Markdown("### πŸ› οΈ Agent Workspaces")
96
 
97
- with gr.Tabs() as workspace_tabs:
98
- # Feature (i): News Debate
 
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
- debate_input = gr.Textbox(
102
  label="Your Stance",
103
- placeholder="e.g., Electric vehicles are flawless answers to climate change."
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=debate_input
112
  )
113
- debate_btn = gr.Button("Deploy Counter-Argument & Score", variant="primary")
114
 
115
- # Feature (ii): News Snippet Generalizer
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
- generalizer_input = gr.Textbox(
119
  label="Complex News Snippet",
120
- lines=5,
121
- placeholder="Paste news column or agency reports here..."
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 Q3 fiscal evaluations."],
126
- ["The ecosystem validation vectors indicate substantial degradation in sub-surface lithospheric layers owing to chemical-heavy manufacturing runoffs, sparking secondary socio-economic compliance friction."]
127
  ],
128
- inputs=generalizer_input
129
  )
130
- generalizer_btn = gr.Button("Generalize for Easy Understanding", variant="primary")
131
 
132
- # Replaced deprecated gr.Spacer() with native HTML margin block
133
- gr.HTML("<div style='height: 15px;'></div>")
134
 
135
- # Advanced Parameters Accordion (Inspired by Screenshot 579)
136
  with gr.Accordion("βš™οΈ Advanced Agent Parameter Configurations", open=False):
137
- system_prompt_box = gr.TextArea(
138
- label="System Prompt Context Injection",
139
  value=(
140
- "You are a sophisticated dual-purpose NLP system operating on a base CPU node. "
141
- "If handling a debate: provide a direct, logical counter-argument and end with a bolded 'Argument Logic Score: X/10'. "
142
- "If handling a generalization: break down the complex text into clear, simple, scannable bullet points."
143
  ),
144
- lines=4
145
  )
146
- max_new_tokens_slider = gr.Slider(minimum=32, maximum=512, value=256, step=16, label="Max new tokens")
147
- temperature_slider = gr.Slider(minimum=0.1, maximum=2.0, value=0.6, step=0.1, label="Temperature")
148
- top_p_slider = gr.Slider(minimum=0.10, maximum=1.00, value=0.90, step=0.05, label="Top-p (Nucleus Sampling)")
149
 
150
- # RIGHT-HAND COLUMN: Status Cards and Live Streamed Outputs (Inspired by Screenshot 564)
151
  with gr.Column(scale=1):
152
  gr.Markdown("### πŸ–₯️ Active Output Stream")
153
- output_display = gr.Markdown(value="*System ready. Select a workspace on the left panel and click compile.*")
 
 
154
 
155
  # ==========================================
156
- # 5. CONTROLLER & EVENT MAPPING
157
  # ==========================================
158
- # Map Debate Event
159
- debate_btn.click(
160
- fn=lambda inp, sys, tokens, temp, top_p: run_agent_task("debate", inp, sys, tokens, temp, top_p),
161
- inputs=[debate_input, system_prompt_box, max_new_tokens_slider, temperature_slider, top_p_slider],
162
- outputs=output_display
163
  )
164
 
165
- # Map Generalization Event
166
- generalizer_btn.click(
167
- fn=lambda inp, sys, tokens, temp, top_p: run_agent_task("generalize", inp, sys, tokens, temp, top_p),
168
- inputs=[generalizer_input, system_prompt_box, max_new_tokens_slider, temperature_slider, top_p_slider],
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())