onenoly11 commited on
Commit
28f9176
Β·
verified Β·
1 Parent(s): 8abc92a

Update Index.html

Browse files
Files changed (1) hide show
  1. Index.html +293 -177
Index.html CHANGED
@@ -1,187 +1,303 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>PiForge - Ethical Mining Booster</title>
7
- <link rel="manifest" href="manifest.json">
8
- <link rel="icon" href="icon.png">
9
- <style>
10
- body {
11
- font-family: Arial, sans-serif;
12
- background: linear-gradient(135deg, #667eea, #764ba2);
13
- color: white;
14
- text-align: center;
15
- margin: 0;
16
- padding: 20px;
17
- }
18
- .container { max-width: 400px; margin: 0 auto; }
19
- button {
20
- background: #4CAF50;
21
- color: white;
22
- border: none;
23
- padding: 15px 30px;
24
- border-radius: 25px;
25
- cursor: pointer;
26
- margin: 10px;
27
- font-size: 16px;
28
- }
29
- #status { margin: 20px; padding: 15px; background: rgba(255,255,255,0.1); border-radius: 10px; }
30
- #ai-assistant { display: none; margin-top: 20px; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px; }
31
- #chat-messages { height: 200px; overflow-y: auto; margin-bottom: 10px; padding: 10px; background: rgba(0,0,0,0.3); border-radius: 5px; }
32
- </style>
33
- </head>
34
- <body>
35
- <div class="container">
36
- <h1>πŸ”¨ PiForge</h1>
37
- <p>Ethical Mining Booster + AI Assistant</p>
38
-
39
- <div id="status">Ready to boost your Pi mining</div>
40
-
41
- <button id="auth-btn">Start Mining Session</button>
42
- <button id="boost-btn" style="display:none;">Activate Ethical Boost</button>
43
 
44
- <div id="user-info" style="display:none; margin-top: 20px;">
45
- <p>Welcome, <span id="username"></span>!</p>
46
- <p>Ethical Score: <span id="score">0</span></p>
47
- </div>
48
-
49
- <!-- βœ… AI Assistant Section - Add this entire block -->
50
- <div id="ai-assistant">
51
- <h3>🧠 PiForge AI Assistant</h3>
52
- <div id="chat-messages"></div>
53
- <div style="display: flex;">
54
- <input type="text" id="ai-question" placeholder="Ask about Pi mining or development..." style="flex: 1; padding: 10px; border-radius: 5px; border: none; margin-right: 10px;">
55
- <button onclick="askDeepSeek()" style="padding: 10px 15px; background: #2196F3; border: none; border-radius: 5px; color: white;">Ask</button>
56
- </div>
57
- </div>
58
- </div>
59
-
60
- <script src="https://sdk.minepi.com/pi-sdk.js"></script>
61
-
62
- <script>
63
- // Pi SDK Initialization
64
- document.addEventListener('DOMContentLoaded', async () => {
65
- try {
66
- await Pi.init({ version: "2.0", sandbox: false });
67
- document.getElementById('status').textContent = 'Pi SDK Ready. Authenticate to begin.';
68
- document.getElementById('auth-btn').style.display = 'block';
69
- } catch (err) {
70
- document.getElementById('status').textContent = 'Pi SDK Init Failed: ' + err.message;
71
- }
72
- });
73
-
74
- // Auth Button Handler - UPDATED WITH AI
75
- document.getElementById('auth-btn').addEventListener('click', async () => {
76
- try {
77
- const scopes = ['username', 'payments'];
78
- const authResult = await Pi.authenticate(scopes, onIncompletePaymentFound);
79
 
80
- // βœ… Show AI Assistant after successful authentication
81
- showAIAssistant();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- document.getElementById('status').textContent = `Welcome, ${authResult.user.username}!`;
84
- document.getElementById('username').textContent = authResult.user.username;
85
- document.getElementById('user-info').style.display = 'block';
86
- document.getElementById('boost-btn').style.display = 'block';
87
 
88
- } catch (err) {
89
- document.getElementById('status').textContent = 'Auth Failed: ' + err.message;
90
- }
91
- });
92
-
93
- // βœ… AI Assistant Function
94
- function showAIAssistant() {
95
- document.getElementById('ai-assistant').style.display = 'block';
96
- // Add welcome message
97
- const chat = document.getElementById('chat-messages');
98
- chat.innerHTML = `<div style="text-align: left; margin: 10px 0; padding: 10px; background: rgba(255,255,255,0.2); border-radius: 5px;">
99
- <b>DeepSeek:</b> Welcome! I'm your Pi Network AI assistant. Ask me about mining strategies, ethical scoring, or app development!
100
- </div>`;
101
- }
102
-
103
- // DeepSeek AI Integration
104
- async function askDeepSeek() {
105
- const question = document.getElementById('ai-question').value;
106
- const chat = document.getElementById('chat-messages');
107
-
108
- if (!question.trim()) return;
109
-
110
- // Add user message
111
- chat.innerHTML += `<div style="text-align: right; margin: 10px 0;"><b>You:</b> ${question}</div>`;
112
-
113
- // Show loading
114
- const loadingId = 'loading-' + Date.now();
115
- chat.innerHTML += `<div id="${loadingId}" style="text-align: left; margin: 10px 0;"><i>DeepSeek is thinking...</i></div>`;
116
- chat.scrollTop = chat.scrollHeight;
117
-
118
- try {
119
- // Call your HF Space API
120
- const response = await fetch('https://onenoly11-piforge.hf.space/run/predict', {
121
- method: 'POST',
122
- headers: {
123
- 'Content-Type': 'application/json',
124
- },
125
- body: JSON.stringify({
126
- data: [question, []]
127
- })
128
- });
129
 
130
- const data = await response.json();
 
 
 
 
 
 
131
 
132
- // Remove loading
133
- document.getElementById(loadingId).remove();
 
 
 
 
134
 
135
- // Add AI response
136
- if (data && data.data && data.data[0]) {
137
- chat.innerHTML += `<div style="text-align: left; margin: 10px 0; padding: 10px; background: rgba(255,255,255,0.2); border-radius: 5px;"><b>DeepSeek:</b> ${data.data[0]}</div>`;
138
- } else {
139
- chat.innerHTML += `<div style="text-align: left; margin: 10px 0; padding: 10px; background: rgba(255,107,53,0.2); border-radius: 5px;"><b>DeepSeek:</b> ${getFallbackResponse(question)}</div>`;
140
- }
141
- } catch (error) {
142
- document.getElementById(loadingId).remove();
143
- chat.innerHTML += `<div style="text-align: left; margin: 10px 0; padding: 10px; background: rgba(255,107,53,0.2); border-radius: 5px;"><b>DeepSeek:</b> ${getFallbackResponse(question)}</div>`;
144
- }
 
145
 
146
- document.getElementById('ai-question').value = '';
147
- chat.scrollTop = chat.scrollHeight;
148
- }
149
-
150
- function getFallbackResponse(question) {
151
- const lowerQ = question.toLowerCase();
152
- if (lowerQ.includes('mining')) return "For optimal Pi mining: mine daily, maintain security circle, and use apps like PiForge for bonuses. The mining rate adjusts based on network participation.";
153
- if (lowerQ.includes('sdk')) return "Pi SDK uses Pi.authenticate() for login and Pi.createPayment() for transactions. Always test in sandbox mode first and follow Pi's developer guidelines.";
154
- if (lowerQ.includes('ethical')) return "Ethical scoring evaluates transparency, community benefit, and sustainability. Projects with 691+ resonance get 15% mining boosts.";
155
- return "I can help with Pi Network mining strategies, app development, SDK usage, and ethical project evaluation. What specific area interests you?";
156
- }
157
-
158
- // Your existing payment functions
159
- document.getElementById('boost-btn').addEventListener('click', async () => {
160
- try {
161
- const paymentData = {
162
- amount: 0.1,
163
- memo: "PiForge Ethical Mining Boost - Supporting transparent community growth",
164
- metadata: { type: 'mining_boost' }
165
- };
166
 
167
- const payment = await Pi.createPayment(paymentData, {
168
- onReadyForServerApproval: (paymentId) => {
169
- document.getElementById('status').textContent = 'Boost activating...';
170
- },
171
- onReadyForServerCompletion: (paymentId, txid) => {
172
- document.getElementById('status').textContent = 'Ethical boost activated! +15% mining rate';
173
- document.getElementById('score').textContent = '750';
174
- }
175
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
- } catch (error) {
178
- document.getElementById('status').textContent = 'Boost failed: ' + error.message;
179
- }
180
- });
181
-
182
- function onIncompletePaymentFound(payment) {
183
- console.log('Incomplete payment:', payment);
184
- }
185
- </script>
186
- </body>
187
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import requests
4
+ import json
5
+ import time
6
+ from huggingface_hub import InferenceClient
7
+
8
+ # Load tokens securely
9
+ HF_TOKEN = os.getenv("HF_TOKEN")
10
+ DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
11
+
12
+ class AdvancedDeepSeekAssistant:
13
+ def __init__(self):
14
+ self.hf_client = InferenceClient(token=HF_TOKEN)
15
+ self.deepseek_api_key = DEEPSEEK_API_KEY
16
+ self.conversation_history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ def query_deepseek_advanced(self, message, use_advanced=True):
19
+ """Enhanced DeepSeek query with full API access"""
20
+ try:
21
+ if use_advanced and self.deepseek_api_key:
22
+ # Use official DeepSeek API with full capabilities
23
+ headers = {
24
+ "Authorization": f"Bearer {self.deepseek_api_key}",
25
+ "Content-Type": "application/json"
26
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ # Build conversation context
29
+ messages = [
30
+ {
31
+ "role": "system",
32
+ "content": """You are DeepSeek AI, a Pi Network and blockchain expert integrated into PiForge.
33
+
34
+ SPECIAL CAPABILITIES:
35
+ - Pi Network mining optimization
36
+ - Ethical scoring algorithms
37
+ - Smart contract development
38
+ - Blockchain architecture
39
+ - SDK integration guidance
40
+ - Community building strategies
41
+
42
+ Provide detailed, actionable advice. You can write code, analyze projects, and suggest improvements."""
43
+ }
44
+ ]
45
 
46
+ # Add conversation history for context
47
+ for msg in self.conversation_history[-6:]: # Keep last 6 exchanges
48
+ messages.append(msg)
 
49
 
50
+ # Add current message
51
+ messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ payload = {
54
+ "model": "deepseek-chat",
55
+ "messages": messages,
56
+ "max_tokens": 1000,
57
+ "temperature": 0.7,
58
+ "stream": False
59
+ }
60
 
61
+ response = requests.post(
62
+ "https://api.deepseek.com/v1/chat/completions",
63
+ headers=headers,
64
+ json=payload,
65
+ timeout=30
66
+ )
67
 
68
+ if response.status_code == 200:
69
+ result = response.json()
70
+ ai_response = result["choices"][0]["message"]["content"]
71
+
72
+ # Update conversation history
73
+ self.conversation_history.append({"role": "user", "content": message})
74
+ self.conversation_history.append({"role": "assistant", "content": ai_response})
75
+
76
+ return ai_response
77
+ else:
78
+ raise Exception(f"API Error: {response.status_code}")
79
 
80
+ else:
81
+ # Fallback to HF Inference
82
+ return self.query_deepseek_hf(message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ except Exception as e:
85
+ print(f"DeepSeek Advanced Error: {e}")
86
+ return self.query_deepseek_hf(message)
87
+
88
+ def query_deepseek_hf(self, message):
89
+ """Fallback to HF Inference API"""
90
+ try:
91
+ prompt = f"""As a Pi Network and blockchain expert, provide detailed help:
92
+
93
+ Question: {message}
94
+
95
+ Provide comprehensive, actionable advice about:
96
+ - Pi Network development and mining
97
+ - Ethical scoring systems
98
+ - Blockchain technology
99
+ - Code examples when relevant
100
+ - Best practices and optimization
101
+
102
+ Answer:"""
103
+
104
+ response = self.hf_client.text_generation(
105
+ prompt,
106
+ model="deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct",
107
+ max_new_tokens=800,
108
+ temperature=0.7,
109
+ do_sample=True
110
+ )
111
+ return response
112
+ except Exception as e:
113
+ return f"πŸ€– **DeepSeek Assistant**: I'm here to help with Pi Network development! Currently, I can provide guidance on mining optimization, ethical scoring, and app development. (Error: {str(e)})"
114
+
115
+ def analyze_proposal_advanced(self, proposal_text):
116
+ """Use DeepSeek to analyze ethical proposals"""
117
+ analysis_prompt = f"""
118
+ Analyze this Pi Network project proposal for ethical scoring:
119
+
120
+ PROPOSAL: {proposal_text}
121
+
122
+ Please evaluate based on:
123
+ 1. Transparency and honesty
124
+ 2. Community benefit value
125
+ 3. Technical feasibility
126
+ 4. Long-term sustainability
127
+ 5. Alignment with Pi Network principles
128
+
129
+ Provide:
130
+ - Strengths and weaknesses
131
+ - Specific improvement suggestions
132
+ - Ethical score estimate (0-1000)
133
+ - Resonance level prediction
134
+
135
+ ANALYSIS:
136
+ """
137
+
138
+ return self.query_deepseek_advanced(analysis_prompt)
139
+
140
+ def generate_code_help(self, topic):
141
+ """Generate code examples and technical help"""
142
+ code_prompt = f"""
143
+ As a technical expert, provide code examples and implementation guidance for:
144
+
145
+ TOPIC: {topic}
146
+
147
+ Please include:
148
+ - Relevant code snippets (JavaScript/Python)
149
+ - Step-by-step implementation guide
150
+ - Best practices and security considerations
151
+ - Common pitfalls to avoid
152
+
153
+ Focus on practical, runnable code examples.
154
+ """
155
+
156
+ return self.query_deepseek_advanced(code_prompt)
157
+
158
+ # Initialize advanced assistant
159
+ advanced_assistant = AdvancedDeepSeekAssistant()
160
+
161
+ def ethical_audit_with_ai_analysis(proposal_text, deep_analysis=False):
162
+ """Enhanced ethical audit with AI analysis"""
163
+ # Basic scoring
164
+ base_score = min(1000, max(600, len(proposal_text) * 2))
165
+ resonance = (base_score * 0.7 + 80 * 3) // 10
166
+ boost = 15 if resonance >= 691 else 0
167
+
168
+ audit_results = {
169
+ "ethical_score": base_score,
170
+ "resonance": resonance,
171
+ "mining_boost": boost,
172
+ "proposal_id": f"prop_{int(time.time())}"
173
+ }
174
+
175
+ # AI Analysis if requested
176
+ ai_analysis = ""
177
+ if deep_analysis and proposal_text.strip():
178
+ ai_analysis = advanced_assistant.analyze_proposal_advanced(proposal_text)
179
+ else:
180
+ ai_analysis = "Enable 'Deep Analysis' for AI-powered project evaluation and improvement suggestions."
181
+
182
+ return audit_results, ai_analysis
183
+
184
+ def chat_with_deepseek_advanced(message, history, use_advanced=True):
185
+ """Advanced chat with conversation history"""
186
+ response = advanced_assistant.query_deepseek_advanced(message, use_advanced)
187
+ return response
188
+
189
+ # Create enhanced Gradio interface
190
+ with gr.Blocks(theme=gr.themes.Soft(), title="PiForge + DeepSeek Pro") as demo:
191
+ gr.Markdown("""
192
+ # πŸ”¨ PiForge Ethical Dual-Forge
193
+ ## πŸ€– Powered by DeepSeek AI Pro
194
+
195
+ *Advanced AI assistance for Pi Network development and ethical mining*
196
+ """)
197
+
198
+ with gr.Tab("πŸ’¬ DeepSeek Pro Chat"):
199
+ gr.Markdown("### Advanced AI Assistant with Full Context")
200
+
201
+ with gr.Row():
202
+ with gr.Column(scale=1):
203
+ advanced_toggle = gr.Checkbox(
204
+ label="Use Advanced DeepSeek API",
205
+ value=True,
206
+ info="Full capabilities with conversation memory"
207
+ )
208
+ clear_chat = gr.Button("Clear Conversation History")
209
 
210
+ with gr.Column(scale=4):
211
+ chatbot = gr.Chatbot(
212
+ label="DeepSeek Pro Conversation",
213
+ height=400,
214
+ show_copy_button=True
215
+ )
216
+
217
+ msg = gr.Textbox(
218
+ label="Your question",
219
+ placeholder="Ask about Pi mining, code examples, ethical scoring, or blockchain development...",
220
+ lines=2
221
+ )
222
+
223
+ def respond(message, chat_history, use_advanced):
224
+ bot_message = chat_with_deepseek_advanced(message, chat_history, use_advanced)
225
+ chat_history.append((message, bot_message))
226
+ return "", chat_history
227
+
228
+ def clear_history():
229
+ advanced_assistant.conversation_history.clear()
230
+ return None
231
+
232
+ msg.submit(respond, [msg, chatbot, advanced_toggle], [msg, chatbot])
233
+ clear_chat.click(clear_history, None, chatbot)
234
+
235
+ with gr.Tab("πŸ” Advanced Ethical Audit"):
236
+ gr.Markdown("### AI-Powered Project Analysis")
237
+
238
+ with gr.Row():
239
+ with gr.Column():
240
+ proposal = gr.Textbox(
241
+ label="Project Proposal",
242
+ placeholder="Describe your project in detail for comprehensive ethical analysis...",
243
+ lines=5
244
+ )
245
+ deep_analysis = gr.Checkbox(
246
+ label="Enable Deep AI Analysis",
247
+ value=True,
248
+ info="Get detailed project evaluation from DeepSeek"
249
+ )
250
+ analyze_btn = gr.Button("Run Advanced Analysis", variant="primary")
251
+
252
+ with gr.Column():
253
+ audit_output = gr.JSON(label="Audit Results")
254
+ ai_analysis = gr.Markdown(
255
+ label="DeepSeek Analysis",
256
+ show_copy_button=True
257
+ )
258
+
259
+ analyze_btn.click(
260
+ ethical_audit_with_ai_analysis,
261
+ inputs=[proposal, deep_analysis],
262
+ outputs=[audit_output, ai_analysis]
263
+ )
264
+
265
+ with gr.Tab("πŸ’» Code & Development"):
266
+ gr.Markdown("### Technical Implementation Help")
267
+
268
+ code_topic = gr.Textbox(
269
+ label="What do you need help coding?",
270
+ placeholder="e.g., 'Pi SDK authentication', 'ethical scoring algorithm', 'blockchain integration'...",
271
+ lines=3
272
+ )
273
+ code_btn = gr.Button("Get Code Help")
274
+ code_output = gr.Markdown(
275
+ label="DeepSeek Code Assistance",
276
+ show_copy_button=True
277
+ )
278
+
279
+ def get_code_help(topic):
280
+ return advanced_assistant.generate_code_help(topic)
281
+
282
+ code_btn.click(get_code_help, inputs=code_topic, outputs=code_output)
283
+
284
+ with gr.Tab("πŸ“š Quick Templates"):
285
+ gr.Markdown("### Common Pi Development Questions")
286
+
287
+ template_questions = [
288
+ "How to implement Pi SDK authentication?",
289
+ "Best practices for ethical scoring algorithms?",
290
+ "How to optimize Pi mining strategy?",
291
+ "Creating a mining boost feature?",
292
+ "Pi App Store submission guidelines?",
293
+ "Smart contract integration with Pi?"
294
+ ]
295
+
296
+ for i, question in enumerate(template_questions):
297
+ gr.Button(question).click(
298
+ lambda q=question: advanced_assistant.query_deepseek_advanced(q, True),
299
+ outputs=msg
300
+ )
301
+
302
+ if __name__ == "__main__":
303
+ demo.launch(share=True)