# Project export: Health Insurance 4 Dummies

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 10.0
- Tagline: Predicts and Explain health insurance costs on personal info.
- Devpost: https://devpost.com/software/health-insurance-for-dummys
- GitHub: https://github.com/jjin43/CalHack2023
- Video: https://www.youtube.com/embed/ie89gtE65rY?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Result: winner (Best Use of InterSystems IntegratedML)
- Team: 1 GitHub contributor(s) — Justin Jin (20 commits)

## Devpost submission (written by the team)

### Inspiration

💪🏼 Health insurance, everyone needs it, no one wants to pay for it. As soon-will-be adults, health insurance has been a growing concern. Since a simple ambulance ride easily costs up to thousands of dollars, not having health insurance is a terrible decision in the US. But how much are you supposed to pay for it? Insurance companies publish their rates, but just having formulas doesn't tell me anything about if they are ripping me off, especially for young adults having never paid for health insurance.

### What it does

? 🔍 Thus, to prevent being ripped off on health insurance after leaving our parents' household. We have developed Health Insurance 4 Dummies. A website utilizing a machine learning model that determines a fair estimate for the annual costs of health insurance, based on user inputs of their personal information. It also uses a LMM to provide detailed information on the composition of the cost.

### How we built it

👷🏼‍♀️ The front-end is built using convex-react, creating an UI that takes inputs from the user. The backend is built using python-flask, which communicates with remote services, InterSystems and Together.AI. The ML model is a feed-forward neural network (MLP) for predicting the cost is built on InterSystems using the H2O ML workflow library, trained on a dataset consist of individual's information and their annual rate for health insurance. The explanation of costs is created using Together.AI's Llama-2 model.

### Challenges we ran into

🔨 Full-stack development is tedious, especially when the functions require remote resources. Finding good datasets to train the model. Authentication in connecting and accessing the trained model on InterSystem using their IRIS connection driver. Choosing the right model to use from Together.AI.

### Accomplishments we're proud of

⭐ Trained and accessed ML model on a remote database open possibility for massive datasets, integrating LMMs to provide automated information.

### What we learned

📖 Full-Stack Development skills, ML model training and utilizing. Accessing remote services using APIs, TLS authentication.

### What's next

for Health Insurance 4 Dummys 🔮 Gather larger datasets to make more parameters available and give more accurate predictions.

## README (from the GitHub repository)

# Hleath-Insurance-4-Dummies
CalHack 10.0 2023 - Table 46

`[InterSystems Challenge: 2nd Place]`
## DevPost/Video Demo Link : 
https://devpost.com/software/health-insurance-for-dummys

## Descriptions:
Choosing the right health insurance is a major concern, especially for young adults. Health Insurance 4 Dummies aims to simplify this complex decision-making process by providing a fair estimate of annual health insurance costs based on user inputs, and using an AI language model to justify the cost.

## Commands to Launch Servers
* FrontEnd - in the /flaskapp directory: run `python flaskapp.py`
* BackEnd - in the /reactapp directory: run `npm run dev`
* webpage url: `http://localhost:5173/`

## Structure
* FrontEnd: Convex-React-Vite
* BackEnd: Python Flask
* ML Model Training: InterSystems-ML_Integration
* AI Response: TogetherAI-Llama-2


## Detected evidence (automated analysis)

Indexed codebase: 12 recognized source files, 13 KB.
- CSS (language) — detected in the code
- Flask (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- SQL (language) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (19 of 19)

```
flaskback/data/CSV_ENUM_KEYS.txt
flaskback/data/health_insurance_DataSample.csv
flaskback/data/intersystems_irispython-3.2.0-py3-none-any.whl
flaskback/flaskapp.py
flaskback/interSys.py
flaskback/requirements.txt
flaskback/static/results.css
flaskback/templates/results.html
flaskback/togetherAI.py
reactapp/.eslintrc.cjs
reactapp/.gitignore
reactapp/index.html
reactapp/package.json
reactapp/src/App.css
reactapp/src/App.jsx
reactapp/src/index.css
reactapp/src/main.jsx
reactapp/vite.config.js
README.md
```

### Dependencies

- flaskback/requirements.txt: .@/data/intersystems_irispython-3.2.0-py3-none-any.whl, Flask, json, ssl, subprocess, together
- reactapp/package.json: @types/react@^18.2.15, @types/react-dom@^18.2.7, @vitejs/plugin-react-swc@^3.3.2, eslint@^8.45.0, eslint-plugin-react@^7.32.2, eslint-plugin-react-hooks@^4.6.0, eslint-plugin-react-refresh@^0.4.3, react@^18.2.0, react-dom@^18.2.0, vite@^4.4.5

### Recent commits (newest first)

- Update README.md
- Update README.md
- Update README.md
- Update README.md
- Update README.md
- Update README.md
- Removed Sensitive Data
- Merge branch 'main' of https://github.com/jjin43/CalHack2023
- Removed all sensitive data
- Update README.md
- Update README.md
- Update README.md
- Last update
- front end css
- Kaly/Paviet added front end codes
- AI minor param bug fix
- ALL functionalities finalized, combined Kaly's commit.
- minor bugs, html scrpit tag in react/index.html
- fixed css directory
- readme

## Key source files (fetched from GitHub, selected and truncated for size)

### flaskback/requirements.txt

```
./data/intersystems_irispython-3.2.0-py3-none-any.whl
Flask
ssl
together
json
subprocess
```

### reactapp/package.json

```
{
  "name": "reactapp",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.15",
    "@types/react-dom": "^18.2.7",
    "@vitejs/plugin-react-swc": "^3.3.2",
    "eslint": "^8.45.0",
    "eslint-plugin-react": "^7.32.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.3",
    "vite": "^4.4.5"
  }
}

```

### reactapp/src/main.jsx

```javascript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)



```

### reactapp/src/App.jsx

```javascript
import { useState } from 'react'
import './App.css'
import Particles from 'react'

function App() {

  return (
    <>
    <div class="title-container">    
      <h1 className="Title">Health Insurance 4 Dummies</h1>
      <img src="src\assets\open-book-doodle.png" alt='health icon' class='header-icon'></img>
    </div>
    <div className="card">
      <form action="http://localhost:5000/submit" method='POST' id='form1'>
        <label htmlFor='age'>Age:</label>
        <input type='number' name='age' id='ageX' required/>
        

        <label htmlFor='sex'>Sex:</label>
        <select name="sex" id='sexX' required>
          <option value="1"> Male </option>
          <option value="0"> Female </option>
        </select>

        <label htmlFor='bmi'>BMI:</label>
        <input type='number' name='bmi' id='bmiX' required />

        <label htmlFor='children'>Number of Children:</label>
        <input type='number' name='children' id='childrenX' required/>

        <label htmlFor='smoker'>Smoker:</label>
        <select name='smoker' id='smokerX' required>
          <option value="0"> No </option>
          <option value="1"> Yes </option>
        </select>

        <label htmlFor='region'>US-Region:</label>
        <select name='region' id='regionX' required>
          <option value="1">  Northwest  </option>
          <option value="2"> Northeast </option>
          <option value="3"> Southwest </option>
          <option value ="4"> Southeast </option>
        </select>
        <div>
          <input type='submit' id='calcButton' value="Calculate" form='form1'/>
        </div>
      </form>
    
    </div>
    </>
  )
}

export default App      



```

### reactapp/vite.config.js

```javascript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})

```

### reactapp/index.html

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Health Insurance 4 Dummies</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript" src="src/buttonDisabler.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

```

### flaskback/togetherAI.py

```python
import together

together.api_key = "..."

def chat(predict, age, sex, bmi, children, smoker, region):

    # age, sex, bmi, children, smoker, region
    if smoker=="Yes":
        smoker = "is a smoker"
    else:
        smoker = "doesn't smokes"

    print("IN CHAT()")
    input = "Given a person's information, age of %s, %s, BMI of %s, with %s children, %s, and lives in %s region of US, use this person's information to explain their health insurance cost. Format your response as a list." %(age, sex, bmi, children, smoker, region)
    output = together.Complete.create(
        prompt = "[INST] %s [/INST]" % (input), 
        model = "togethercomputer/llama-2-13b-chat", 
        max_tokens = 400,
        temperature = 0.1,
        top_k = 40,
        top_p = 0.90,
        repetition_penalty = 1.1,
        stop = ["7.", '[INST]', '</s>']
    )

    response = str(output['output']['choices'][0]['text'])
    if response.strip().endswith("7."):
        response = response.strip()[:-2]
    print(response)
    return response

```

### flaskback/interSys.py

```python
import iris
import os
import ssl

def acessDB(age, sex, bmi, children, smoker, region):
    sslcontext = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile="./data/certificateSQLaaS.pem")

    connection_str = "..."
    port = 443
    namespace = "USER"
    username = "SQLAdmin"
    password = "..."
    arr = []

    connection = iris.connect(connection_str, port, namespace, username, password, sslcontext=sslcontext)
    cursor = connection.cursor()
    try:
        cursor.execute("INSERT INTO PredictInput(age, sex, bmi, children, smoker, region) VALUES(%s, %s, %s, %s, %s, %s)" % (age, sex, bmi, children, smoker, region))
        cursor.execute("SELECT TOP(1) PREDICT(HealthInsuranceModel use HealthInsuranceModel_v1) as prediction FROM SQLUser.PredictInput")
        arr = cursor.fetchmany(1)
        cursor.execute("DELETE From PredictInput")
        pass
    except Exception as ex:
        print(ex)
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()
        print(arr[0])
        return arr[0]
```

### flaskback/flaskapp.py

```python
import subprocess
import togetherAI
import interSys
from flask import Flask, request, render_template
import json

app = Flask(__name__)

@app.route('/submit', methods=['GET','POST'])
def submit():
    # Recieving data from React
    # clear all data
    # age, sex, bmi, children, smoker, region = None,None,None,None,None,None
    dataArr = []
    aiResponse = ''
    # get atrributes from front end : 
    # age, sex, bmi, children, smoker, region
    age = request.form.get('age')
    sex = request.form.get('sex')
    children = request.form.get('children')
    bmi = request.form.get('bmi')
    smoker = request.form.get('smoker')
    region = request.form.get('region')
    # print("age="+str(age), "sex="+str(sex), "bmi="+str(bmi), "children="+str(children), "smoker="+str(smoker), "region"+str(region))
    if (age and bmi and children and sex and smoker and region):
        predict = interSys.acessDB(age, sex, bmi, children, smoker, region)
        #print(predict)

        if(sex=='1'):
            sex = "male"
        elif(sex=='0'):
            sex = "female"
        
        if(smoker=='1'):
            smoker = "Yes"
        elif(smoker=='0'):
            smoker = "No"

        if(region=='1'):
            region = "northwest"
        elif(region=='2'):
            region = "northeast"
        elif(region=='3'):
            region = "southwest"
        elif(region=='4'):
            region = "southeast"
        # pass arr to Generative AI
        predict = round(float(predict[0]),2)
        predict = str(predict)
        aiResponse = togetherAI.chat(predict, age, sex, bmi, children, smoker, region)  

        # aiResponse = '<p>' + aiResponse
        # for i in range(0,len(aiResponse)-3):
        #     if aiResponse[i].isdigit() and aiResponse[i+1] == '.':
        #         aiResponse[:i-1] + '</p> <p>' + aiResponse[i-1:]
        # aiResponse = aiResponse +'.' + '</p>'

    else: return "All Data Must be Provided."      
    # Send data to Reacts
    return render_template('results.html',predict=predict,age=age,sex=sex,bmi=bmi,children=children,smoker=smoker,region=region,aiResponse=aiResponse)



if __name__ == "__main__":
    app.run(host="localhost", port=5000)
```

### flaskback/templates/results.html

```html
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/results.css') }}">
</head>
<body>
    
    <h1 className="Title">Health Insurance Cost Predicton</h1>
    
    <h2 class="card">Your Predicted Health Insurance Annual Cost is:&nbsp&nbsp{{predict}} </h2> 
        <!-- <h2> </h2> -->

<div class="test">
    <div class="card">
        <h3>Profile:</h3>
        <body>
            <br>Age: {{age}}</br>
            <br>Sex: {{sex}}</br>
            <br>BMI: {{bmi}}</br>
            <br># of Children: {{children}}</br>
            <br>Smoker: {{smoker}}</br>
            <br>US region: {{region}}</br>
        </body>
    </div>
    <div class="card">
    <h3>InsuranceBot's Explaination:<h3>
        <body> {{aiResponse}}</body>
    </div>

</div>
</body>
</html>


```

[3 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]