File size: 10,747 Bytes
68754bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# app.py - Ai Forge: Ethical Audit + AI App Builder (Streamlit Version)
import streamlit as st
import hashlib
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime

# Page config
st.set_page_config(
    page_title="Ai Forge: Ethical Audit + AI App Builder",
    page_icon="πŸ€–",
    layout="wide"
)

# 🍟 PIFORGE DUAL-PLATFORM: AUDIT + APP BUILDER
PIFORGE_CSS = """
<style>
.piforge-premium-header {
    background: linear-gradient(135deg, #FF6B6B 0%, #FFE66D 50%, #1A535C 100%);
    padding: 30px;
    border-radius: 20px;
    color: white;
    text-align: center;
    margin-bottom: 30px;
    border: 4px solid #4ECDC4;
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}
.audit-badge {
    background: linear-gradient(45deg, #667eea, #764ba2);
    color: white;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 16px;
    font-weight: bold;
}
.builder-badge {
    background: linear-gradient(45deg, #FFD700, #FF6B00);
    color: #1A535C;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 16px;
    font-weight: bold;
}
</style>
"""

class PiForgeQualiaOracle:
    def get_qualia_score(self, impact_text: str) -> int:
        # POWERFUL ETHICAL AUDIT ENGINE
        if not impact_text: return 500
        text_lower = impact_text.lower()
        score = 500
        ethical_dimensions = {
            "community": 80, "inclusion": 90, "transparent": 85, "fair": 80,
            "privacy": 75, "education": 75, "help": 70, "empower": 85,
            "decentralized": 65, "open": 70, "accessible": 75
        }
        for principle, boost in ethical_dimensions.items():
            if principle in text_lower: score += boost
        score += min(200, len(impact_text) // 2)
        return min(1000, max(0, score))

qualia_oracle = PiForgeQualiaOracle()

# 🎯 CORE AUDIT FUNCTIONS (Your Original System)
def velvet_verdict(a, b):
    a, b = int(a), int(b)
    if a == 0 or b == 0: return 0
    return (2 * a * b) // (a + b)

def resonance_narrative(r):
    if r >= 800: return "🌟 Resonance blooms: Sovereign sway achieved"
    if r >= 650: return "πŸŒ€ Synthesis stirs: Tender truth tempers the tide"
    if r >= 500: return "πŸ’« Echo invites: A gentle balance"
    return "🌱 Refine the reactive, reflect the reflection"

def plot_triad(veracity, qualia, resonance):
    # AUDIT VISUALIZATION
    labels = ['Veracity', 'Qualia', 'Resonance']
    scores = [veracity/1000, qualia/1000, resonance/1000]
    angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False).tolist()
    scores += scores[:1]
    angles += angles[:1]
    
    fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
    ax.plot(angles, scores, color='magenta', linewidth=2)
    ax.fill(angles, scores, color='cyan', alpha=0.25)
    ax.set_xticks(angles[:-1])
    ax.set_xticklabels(labels)
    ax.set_yticklabels([])
    ax.set_facecolor('#1a1a1a')
    fig.patch.set_facecolor('#1a1a1a')
    plt.title('Ethical Triad Harmony', size=14, color='white', y=1.1)
    return fig

# πŸ” ETHICAL AUDIT SYSTEM
def simple_ethics_check(project_name, description, impact):
    # ORIGINAL AUDIT FUNCTION
    if not description:
        return 0, "πŸ”„ Please describe your project", "Waiting for your vision..."
    
    qualia_score = qualia_oracle.get_qualia_score(impact + " " + description)
    efficiency_score = min(800, len(description) * 2 + 400)
    resonance = velvet_verdict(efficiency_score, qualia_score)
    
    if resonance >= 850:
        verdict = "🎯 EXCELLENT - Strong ethical alignment!"
        confidence = f"Ethical Score: {resonance}/1000 - Community-ready!"
    elif resonance >= 700:
        verdict = "βœ… VERY GOOD - Positive impact potential"
        confidence = f"Ethical Score: {resonance}/1000 - Solid foundation"
    elif resonance >= 550:
        verdict = "πŸ’‘ GOOD - Some refinement opportunities"
        confidence = f"Ethical Score: {resonance}/1000 - Consider community feedback"
    else:
        verdict = "πŸ”„ NEEDS WORK - Rethink ethical approach"
        confidence = f"Ethical Score: {resonance}/1000 - Focus on user benefits"
    
    return resonance, verdict, confidence

def traverse_triad(values, v_weight, impact_txt):
    # EXPERT AUDIT PHASE II (Fixed: using values as proxy for reactive, v_weight as reactive_val)
    reactive_val = int(v_weight)  # Use v_weight as reactive for demo
    qualia_val = qualia_oracle.get_qualia_score(impact_txt)
    resonance_val = velvet_verdict(reactive_val, qualia_val)
    narrative = resonance_narrative(resonance_val)
    plot = plot_triad(reactive_val, qualia_val, resonance_val)
    
    return (f"Reactive: {reactive_val}/1000",
            f"Qualia: {qualia_val}/1000", 
            f"Resonance: {resonance_val}/1000",
            narrative, plot)

# πŸ€– APP BUILDER FUNCTIONS (New Addition)
class PiForgeAppBuilder:
    def generate_testnet_app(self, app_idea, app_type, features):
        base_boost = 5
        feature_boosts = {"community_governance": 3, "pi_rewards": 2, "transparent_audit": 2}
        total_boost = base_boost + sum(feature_boosts.get(f, 0) for f in features)
        return {
            "testnet_mining_boost": min(15, total_boost),
            "app_id": f"testnet_{hashlib.sha256(f'{app_idea}{datetime.now()}'.encode()).hexdigest()[:12]}"
        }

app_builder = PiForgeAppBuilder()

def build_testnet_app(app_idea, app_type, selected_features):
    # NEW APP BUILDER FUNCTION
    if not app_idea:
        return "❌ Please describe your app idea", "", 0, "", ""
    
    app_data = app_builder.generate_testnet_app(app_idea, app_type, selected_features)
    ethical_score = qualia_oracle.get_qualia_score(f"{app_idea} with {selected_features}")
    
    app_blueprint = f"""
    πŸš€ **Testnet App Blueprint**
    🎯 **Ethical Score:** {ethical_score}/1000
    ⚑ **Mining Boost:** +{app_data['testnet_mining_boost']}%
    πŸ“± **App ID:** {app_data['app_id']}
    """
    
    return ("βœ… Testnet App Blueprint Generated!", app_blueprint, 
            app_data['testnet_mining_boost'], app_data['app_id'], "Ready for Testnet!")

# πŸ—οΈ COMPLETE DUAL-PLATFORM INTERFACE
st.markdown(PIFORGE_CSS, unsafe_allow_html=True)

# Header
st.markdown("""
<div class="piforge-premium-header">
    <h1>πŸ”¨ Ο€ Ai Forge Dual-Platform</h1>
    <h3>Ethical Audit System + AI App Builder</h3>
    <p><span class='audit-badge'>πŸ” ETHICAL AUDIT</span> <span class='builder-badge'>πŸ€– APP BUILDER</span></p>
</div>
""", unsafe_allow_html=True)

# Mode selector (though using tabs, keep for future)
mode = st.radio(
    "Choose Ai Forge Platform",
    options=["πŸ” Ethical Audit", "πŸ€– AI App Builder", "πŸ“Š Portfolio"],
    index=0
)

# Tabs for main sections
tab1, tab2 = st.tabs(["πŸ” Ethical Audit", "πŸ€– AI App Builder"])

with tab1:
    st.markdown("### 🌊 Ethical Audit System")
    st.markdown("*Your original powerful ethical assessment platform*")
    
    # Simple Audit
    with st.expander("πŸš€ Simple Audit", expanded=True):
        col1, col2 = st.columns(2)
        with col1:
            project_name = st.text_input("Project Name", value="Community Marketplace")
            description = st.text_area("Description", height=100)
            impact = st.text_area("Impact", height=70)
            if st.button("πŸ” Run Ethical Audit", type="primary"):
                score, verdict, analysis = simple_ethics_check(project_name, description, impact)
                st.session_state.simple_score = score
                st.session_state.simple_verdict = verdict
                st.session_state.simple_analysis = analysis
        
        with col2:
            if 'simple_score' in st.session_state:
                st.metric("Ethical Score", st.session_state.simple_score, delta=None)
                st.text_area("Verdict", value=st.session_state.simple_verdict, height=70)
                st.text_area("Analysis", value=st.session_state.simple_analysis, height=100)
    
    # Expert Audit
    with st.expander("πŸ”¬ Expert Audit"):
        col1, col2 = st.columns(2)
        with col1:
            values = st.text_input("Core Values")
            assumptions = st.text_input("Assumptions")
            impact_text = st.text_area("Impact Narrative", height=100)
            v_weight = st.slider("Veracity Weight", 0, 1000, 600)
            q_weight = st.slider("Qualia Weight", 0, 1000, 400)
            if st.button("🌊 Traverse Ethical Triad", type="primary"):
                verity_out, qualia_out, resonance_out, narrative_out, plot_fig = traverse_triad(values, v_weight, impact_text)
                st.session_state.expert_verity = verity_out
                st.session_state.expert_qualia = qualia_out
                st.session_state.expert_resonance = resonance_out
                st.session_state.expert_narrative = narrative_out
                st.session_state.expert_plot = plot_fig
        
        with col2:
            if 'expert_verity' in st.session_state:
                st.text_area("Reactive Echo", value=st.session_state.expert_verity, height=50)
                st.text_area("Tender Reflection", value=st.session_state.expert_qualia, height=50)
                st.text_area("Resonance Value", value=st.session_state.expert_resonance, height=50)
                st.text_area("Velvet Verdict", value=st.session_state.expert_narrative, height=70)
                st.pyplot(st.session_state.expert_plot)

with tab2:
    st.markdown("### πŸš€ Testnet AI App Builder")
    st.markdown("*Build Pi Testnet apps with ethical scoring*")
    
    col1, col2 = st.columns(2)
    with col1:
        app_idea = st.text_area("App Idea", height=100)
        app_type = st.selectbox("App Type", options=["marketplace", "education", "gaming"])
        features = st.multiselect("Select Features", options=["community_governance", "pi_rewards", "transparent_audit"])
        if st.button("πŸ”¨ Build Testnet App", type="primary"):
            build_status, blueprint, boost, app_id, status_msg = build_testnet_app(app_idea, app_type, features)
            st.session_state.build_status = build_status
            st.session_state.blueprint = blueprint
            st.session_state.boost = boost
            st.session_state.app_id = app_id
            st.session_state.status_msg = status_msg
    
    with col2:
        if 'build_status' in st.session_state:
            st.text_area("Build Status", value=st.session_state.build_status, height=50)
            st.text_area("App Blueprint", value=st.session_state.blueprint, height=200)
            st.metric("Mining Boost %", st.session_state.boost, delta=None)
            st.text_input("App ID", value=st.session_state.app_id, disabled=True)
            st.caption(st.session_state.status_msg)