File size: 3,530 Bytes
bff633e
8804efc
5cc8442
bff633e
2594c65
bff633e
92da69d
 
5cc8442
d003647
92da69d
 
 
 
d003647
92da69d
 
d003647
 
 
 
 
 
 
 
 
92da69d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d003647
92da69d
 
 
 
 
 
bff633e
92da69d
 
 
bff633e
92da69d
bff633e
92da69d
 
 
 
 
 
 
 
 
 
 
 
 
bff633e
92da69d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2594c65
92da69d
 
 
2594c65
92da69d
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
import os
import streamlit as st
import pandas as pd
import mysql.connector
from huggingface_hub import InferenceClient

st.set_page_config(layout="wide", page_title="🧠 SmartHeal AI Dashboard (LLaMA 3.1)")
st.title("🩺 SmartHeal: AI-Generated Dashboard (LLaMA 3.1 Instruct)")

HF_TOKEN = os.environ.get("HF_TOKEN") or st.secrets["HF_TOKEN"]
client = InferenceClient(
    model="meta-llama/Llama-3.1-8B-Instruct",
    token=HF_TOKEN
)

# ------------------- Fetch all tables, schema, samples -------------------
def get_schema_and_samples():
    try:
        conn = mysql.connector.connect(
            host="sg-nme-web545.main-hosting.eu",
            user="u124249738_SmartHealApp",
            password="I^4y1b12y",
            database="u124249738_SmartHealAppDB",
            port=3306,
            connection_timeout=10
        )
        cursor = conn.cursor()
        cursor.execute("SHOW TABLES")
        tables = [t[0] for t in cursor.fetchall()]

        full_prompt = ""
        for table in tables:
            full_prompt += f"\n### Table: {table}\n"
            cursor.execute(f"DESCRIBE {table}")
            for row in cursor.fetchall():
                full_prompt += f"- {row[0]} ({row[1]})\n"

            cursor.execute(f"SELECT * FROM {table} LIMIT 5")
            rows = cursor.fetchall()
            columns = [desc[0] for desc in cursor.description]
            df = pd.DataFrame(rows, columns=columns)
            full_prompt += f"\nSample rows:\n{df.to_markdown(index=False)}\n"

        conn.close()
        return full_prompt
    except Exception as e:
        return f"❌ Error: {e}"

# ------------------- Ask LLaMA to generate HTML dashboard -------------------
def generate_html(schema):
    prompt = f"""
You are a world-class dashboard developer and wound care analytics expert.

Below is the database schema and 5 rows per table from a real wound care system:

{schema}

Please build a clean, mobile-responsive HTML dashboard using Bootstrap 5 and Chart.js or Plotly.js.

Requirements:
1. Top KPIs (tiles): Total Patients, Total Wounds, Avg. Wound Area, % Reduction in Area
2. A modern line chart of wound area (area_cm2) over time grouped by wound_id
3. A pie chart showing wound types (from `wounds` table)
4. A searchable table with: patient_id, wound_id, area, created_at
5. Layout must have a soft background, card-like sections, hover effects, bold typography
6. Add a sticky header and use light neumorphic style or silhouette aesthetics
7. Use clean font (like 'Poppins' or 'Lato'), subtle shadows, rounded corners
8. Return only pure HTML+CSS+JS. No markdown, no ``` blocks.

Respond with only valid HTML.
"""
    response = client.chat.completions.create(
        model="meta-llama/Llama-3.1-8B-Instruct",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content

# ------------------- Streamlit flow -------------------
schema_summary = get_schema_and_samples()

if schema_summary.startswith("❌"):
    st.error(schema_summary)
    st.stop()

with st.expander("πŸ“„ View Database Schema + Samples"):
    st.text(schema_summary)

if st.button("πŸš€ Generate HTML Dashboard with LLaMA"):
    with st.spinner("Generating rich HTML dashboard from LLaMA 3.1..."):
        try:
            html_code = generate_html(schema_summary)
            st.success("βœ… AI dashboard ready!")
            st.components.v1.html(html_code, height=1200, scrolling=True)
        except Exception as e:
            st.error(f"❌ LLaMA failed: {e}")