File size: 7,755 Bytes
f0925f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc570bf
f0925f0
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import numpy as np
import json
import os
from groq import Groq
from dotenv import load_dotenv
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime

# Load environment variables
load_dotenv()
GROQ_API_KEY = os.getenv('GROQ_API_KEY')

# Custom CSS to make the page full-windowed
st.markdown(
    """
    <style>
    .stApp {
        max-width: 100%;
        padding: 0;
    }
    .stButton>button {
        width: 100%;
    }
    </style>
    """,
    unsafe_allow_html=True
)

# Helper functions for calculations (from previous_app.py)
def calculate_h2_production(method, water_quantity, energy_input, current_density, voltage):
    """Calculate hydrogen production based on input parameters"""
    method_efficiencies = {
        "Alkaline Electrolysis": 0.65,
        "PEM Electrolysis": 0.75,
        "SOEC": 0.85
    }
    faraday_constant = 96485  # C/mol
    molar_mass_h2 = 2.02  # g/mol
    efficiency = method_efficiencies[method]
    surface_area = water_quantity * 0.1
    current = current_density * surface_area
    time_hours = energy_input / (voltage * current)
    moles_h2 = (current * time_hours * 3600 * efficiency) / (2 * faraday_constant)
    mass_h2 = moles_h2 * molar_mass_h2
    volume_h2 = moles_h2 * 22.4
    return {
        "production_rate_g_per_hour": mass_h2 / time_hours,
        "total_production_g": mass_h2,
        "total_production_L": volume_h2,
        "efficiency": efficiency,
        "operation_time_hours": time_hours
    }

def calculate_cost(method, water_cost, water_purification_cost, energy_source, energy_input, h2_production):
    """Calculate the cost of hydrogen production"""
    energy_costs = {
        "Grid Electricity": 0.12,
        "Solar": 0.08,
        "Wind": 0.06,
        "Nuclear": 0.10,
        "Hydroelectric": 0.07
    }
    operational_costs = {
        "Alkaline Electrolysis": 1.2,
        "PEM Electrolysis": 1.5,
        "SOEC": 1.8
    }
    total_water_cost = water_cost * (h2_production["total_production_g"] / 1000)
    total_purification_cost = water_purification_cost * (h2_production["total_production_g"] / 1000)
    energy_cost_rate = energy_costs[energy_source]
    total_energy_cost = energy_cost_rate * energy_input
    operational_cost_rate = operational_costs[method]
    total_operational_cost = operational_cost_rate * (h2_production["total_production_g"] / 1000)
    total_cost = total_water_cost + total_purification_cost + total_energy_cost + total_operational_cost
    cost_per_kg = total_cost / (h2_production["total_production_g"] / 1000) if h2_production["total_production_g"] > 0 else 0
    return {
        "water_cost": total_water_cost,
        "purification_cost": total_purification_cost,
        "energy_cost": total_energy_cost,
        "operational_cost": total_operational_cost,
        "total_cost": total_cost,
        "cost_per_kg": cost_per_kg
    }

def call_groq_api(user_inputs, production_data, cost_data):
    """Call Groq API with Llama 3 to analyze production parameters and provide recommendations"""
    try:
        client = Groq(api_key=os.environ.get("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"))
    except Exception as e:
        return {"error": f"Failed to initialize Groq client: {str(e)}"}
    
    prompt = f"""
    As a hydrogen production expert, analyze the following electrolysis parameters and provide recommendations for optimization:
    
    Input Parameters:
    - Water Source: {user_inputs['water_source']}
    - Production Method: {user_inputs['production_method']}
    - Energy Source: {user_inputs['energy_source']}
    - Current Density: {user_inputs['current_density']} A/cm²
    - Voltage: {user_inputs['voltage']} V
    - Membrane Material: {user_inputs['membrane']}
    - Electrode Materials: {user_inputs['electrodes']}
    
    Production Results:
    - Production Rate: {production_data['production_rate_g_per_hour']:.2f} g/hour
    - Total Production: {production_data['total_production_g']:.2f} g
    - Efficiency: {production_data['efficiency'] * 100:.1f}%
    - Operation Time: {production_data['operation_time_hours']:.2f} hours
    
    Cost Analysis:
    - Water Cost: ${cost_data['water_cost']:.2f}
    - Purification Cost: ${cost_data['purification_cost']:.2f}
    - Energy Cost: ${cost_data['energy_cost']:.2f}
    - Operational Cost: ${cost_data['operational_cost']:.2f}
    - Total Cost: ${cost_data['total_cost']:.2f}
    - Cost per kg H₂: ${cost_data['cost_per_kg']:.2f}
    
    Please provide:
    1. An efficiency assessment of the current setup
    2. Three specific recommendations to improve efficiency
    3. Three specific recommendations to reduce costs
    4. An ideal parameter configuration based on the provided inputs
    
    Format your response as a structured JSON with these fields:
    {
        "efficiency_assessment": "text analysis",
        "efficiency_recommendations": ["recommendation1", "recommendation2", "recommendation3"],
        "cost_recommendations": ["recommendation1", "recommendation2", "recommendation3"],
        "ideal_parameters": {
            "current_density": value,
            "voltage": value,
            "membrane": "recommendation",
            "electrodes": "recommendation",
            "energy_source": "recommendation"
        },
        "estimated_improvement": {
            "efficiency_increase": "percentage",
            "cost_reduction": "percentage"
        }
    }
    """
    
    try:
        chat_completion = client.chat.completions.create(
            messages=[{"role": "user", "content": prompt}],
            model="llama-3.3-70b-versatile",
            temperature=0.5,
            max_tokens=1024,
            response_format={"type": "json_object"}
        )
        response_content = chat_completion.choices[0].message.content
        return json.loads(response_content)
    except Exception as e:
        return {"error": f"Error calling Groq API: {str(e)}"}

# Function to display the app interface
def show_app_interface():
    """Function to display the app interface"""
    st.title("Hydrogen Production Analysis & Optimization")
    st.write("This is the app interface.")

# Function to display the AI chatbot
def show_chatbot():
    """Function to display the AI chatbot"""
    st.title("AI Chatbot")
    user_input = st.text_input("Ask me anything about hydrogen production:")
    if user_input:
        response = call_groq_api({}, {}, {})
        st.write(response)

# Function to display the landing page
def show_landing_page():
    """Function to display the landing page"""
    st.markdown(
        """
        <div style="text-align: center; padding: 50px;">
            <h1>Ready to Transform Your Hydrogen Projects?</h1>
            <p>Join the hydrogen revolution with AI-powered techno-economic analysis that gives you the competitive edge.</p>
            <button style="padding: 10px 20px; margin: 10px; background-color: #4CAF50; color: white; border: none; border-radius: 5px;" onclick="window.location.href='?page=app'">Request a Demo</button>
            <button style="padding: 10px 20px; margin: 10px; background-color: #1E88E5; color: white; border: none; border-radius: 5px;" onclick="window.location.href='?page=chatbot'">Learn More</button>
        </div>
        """,
        unsafe_allow_html=True
    )

# Main function to handle navigation
def main():
    """Main function to handle navigation between pages"""
    query_params = st.query_params
    page = query_params.get("page", ["landing"])[0]

    if page == "app":
        show_app_interface()
    elif page == "chatbot":
        show_chatbot()
    else:
        show_landing_page()

if __name__ == "__main__":
    main()