# Project export: Midas

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: Midas analyzes traders' facial expressions with Hume API to log data about their emotions as they trade, then using a LLM to provide feedback based on the collected data and guide their trades.
- Devpost: https://devpost.com/software/midas-t5ncua
- GitHub: https://github.com/adithg/Whatdadogdoin
- Result: winner (Best AI x Crypto with Infinity)
- Team: 3 GitHub contributor(s) — yirmea (25 commits), Eduardo Lopez (10 commits), adithg (3 commits)

## Devpost submission (written by the team)

### Inspiration

The intersection between human emotion and technology has been rapidly expanding, providing Data Science and Computer Science majors such as us to explore and push the boundaries of our collective knowledge through new technologies that grow and improve everyday.

### What it does

Midas uses a webcam to process data about traders' facial expressions in real-time, creating and contributing to a user database of processed statistical information about their emotions during their different trades. By pairing information about the trades, their outcomes, and the emotions exhibited throughout, a LLM then generates custom feedback for each user to improve their performance based on their personal emotional data.

### How we built it

Midas was built using a combination of Hume.AI and LLM training. We used Python for the backend as well as front end using REFLEX. Hume was used to get emotional data and face tracking. MindsDB was use for SQL database integration into our LLM.

### Challenges we ran into

Developing an accurate reading of someone's emotions over a period of time and how exactly to train the LLm based on these emotions. Additionally, ensuring user privacy and data security was a concern.

### Accomplishments we're proud of

We successfully created a functional system to analyze traders' emotions during their trades. Integrating emotional data with trade-related information is a unique feature of our project. We're proud of our LLM's ability to generate personalized feedback based on a user's emotional data.

### What we learned

We gained a deeper understanding of emotion tracking, Natural Languge Processing, and data analysis techniques. Additionally, we learned about the challenges and ethical considerations involved in working with user data and privacy.

### What's next

There are several potential future directions for Midas. This might include expanding the types of emotional data collected, conducting user studies to assess the impact of emotional feedback on trading performance, and enhancing the overall user experience. We may also explore opportunities to integrate with trading platforms or provide more detailed analytics for traders. Further development could involve ensuring regulatory compliance in the finance industry and addressing potential privacy concerns. Additionally, we could expand the use of the technology beyond trading, such as in education or mental health applications.

## README (from the GitHub repository)

No README available.

## Detected evidence (automated analysis)

Indexed codebase: 53 recognized source files, 170 KB.
- CSS (language) — detected in the code
- JavaScript (language) — detected in the code
- Next.js (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- SQL (language) — detected in the code
- Tailwind CSS (technology) — detected in the code

## Codebase structure (from repository index)

### Files (66 of 66)

```
antitilt.py
backend.py
encoded_img.txt
facial_expressions.py
hume.ipynb
init.py
predictions.json
quicktest.py
stream_output.txt
trade_emotions.json
webcamHume.py
website/.gitignore
website/.web/.gitignore
website/.web/components/reflex/chakra_color_mode_provider.js
website/.web/components/reflex/radix_themes_color_mode_provider.js
website/.web/env.json
website/.web/jsconfig.json
website/.web/next.config.js
website/.web/package.json
website/.web/pages/_app.js
website/.web/pages/_document.js
website/.web/pages/404.js
website/.web/pages/a-example.js
website/.web/pages/crypto1.js
website/.web/pages/crypto2.js
website/.web/pages/crypto3.js
website/.web/pages/crypto4.js
website/.web/pages/index.js
website/.web/pages/profile.js
website/.web/postcss.config.js
website/.web/reflex.json
website/.web/styles/code/prism.js
website/.web/styles/styles.css
website/.web/styles/tailwind.css
website/.web/tailwind.config.js
website/.web/utils/client_side_routing.js
website/.web/utils/components.js
website/.web/utils/context.js
website/.web/utils/helpers/dataeditor.js
website/.web/utils/state.js
website/.web/utils/theme.js
website/antitilt.py
website/Miscalgos.sql
website/README.md
website/requirements.txt
website/rxconfig.py
website/trade_emotions.json
website/website/__init__.py
website/website/components/__init__.py
website/website/components/cryptobutton.py
website/website/components/humebutton.py
website/website/components/humetable.py
website/website/components/sidebar.py
website/website/pages/__init__.py
website/website/pages/crypto1.py
website/website/pages/crypto2.py
website/website/pages/crypto3.py
website/website/pages/crypto4.py
website/website/pages/example.py
website/website/pages/index.py
website/website/pages/profile.py
website/website/state.py
website/website/styles.py
website/website/templates/__init__.py
website/website/templates/template.py
website/website/website.py
```

### Dependencies

- website/.web/package.json: @chakra-ui/react@^2.6.1, @chakra-ui/system@^2.5.7, @emotion/react@^11.11.0, @emotion/styled@^11.11.0, autoprefixer@10.4.14, axios@1.4.0, focus-visible@5.2.0, framer-motion@^10.16.4, json5@2.2.3, next@13.5.4, next-sitemap@4.1.8, next-themes@0.2.0, postcss@8.4.24, react@18.2.0, react-dom@18.2.0, socket.io-client@4.6.1, tailwindcss@^3.3.2, universal-cookie@4.0.4
- website/requirements.txt: reflex@==0.3.1

### Recent commits (newest first)

- Removed API key from code because repo is public on GitHub
- Removed API key from code because repo is public on GitHub
- final
- fix
- Merge branch 'main' of https://github.com/adithg/Whatdadogdoin
- delta added & dummy data
- fixed
- dummy data add
- plz work
- slay
- Finished emotional analysis function
- optional time
- revert
- remove category
- Merge branch 'main' of https://github.com/adithg/Whatdadogdoin
- rename antitilt
- Finished emotion predictor, need to wrap as function
- started pandas integration
- pandas implement
- Merge branch 'main' of https://github.com/adithg/Whatdadogdoin

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

### website/requirements.txt

```

reflex==0.3.1

```

### website/.web/package.json

```
{
  "name": "reflex",
  "scripts": {
    "dev": "next dev",
    "export": "next build && next export -o _static",
    "export-sitemap": "next build && next-sitemap && next export -o _static",
    "prod": "next start"
  },
  "dependencies": {
    "@chakra-ui/react": "^2.6.1",
    "@chakra-ui/system": "^2.5.7",
    "@emotion/react": "^11.11.0",
    "@emotion/styled": "^11.11.0",
    "axios": "1.4.0",
    "focus-visible": "5.2.0",
    "framer-motion": "^10.16.4",
    "json5": "2.2.3",
    "next": "13.5.4",
    "next-sitemap": "4.1.8",
    "next-themes": "0.2.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "socket.io-client": "4.6.1",
    "tailwindcss": "^3.3.2",
    "universal-cookie": "4.0.4"
  },
  "devDependencies": {
    "autoprefixer": "10.4.14",
    "postcss": "8.4.24"
  }
}

```

### website/website/pages/index.py

```python
"""The home page of the app."""

from website import styles
from website.templates import template
# import antitilt as anti
# from website.components.cryptobutton import actionbutton

import reflex as rx


@template(route="/", title="Home", image="/github.svg")
def index() -> rx.Component:
    """The home page.

    Returns:
        The UI for the home page.
    """
    return rx.hstack(
        rx.box (
            # rx.html('<iframe src="https://beta.hume.ai/playground?mode=webcam" width="500px" height="500px" id="frame1" allow="autoplay; camera; microphone"</iframe>'
            #     ),
            border_width="thick",
            border_color ="pink",
            width= "70%",
            height='70%',
            margin_left="5%",
            paadding_x="5%",
        ),

        rx.box(
            rx.text("On the left is one of the resources provided by Hume at CalHacks 2023, the model looks at the vision and determines someone's emotions using decimals.", color="white"),
            border_width="thick",
            border_color ="green",
            width="30%",
            height="500px",

        ),

        border_width="thick",
        bg="black",
        border_color ="red",
       

    )
```

### website/.web/pages/index.js

```javascript
import { Fragment, useContext, useEffect, useRef, useState } from "react"
import { useRouter } from "next/router"
import { Event, getAllLocalStorageItems, getRefValue, getRefValues, isTrue, preventDefault, refs, spreadArraysOrObjects, uploadFiles, useEventLoop } from "/utils/state"
import { ColorModeContext, EventLoopContext, initialEvents, StateContext } from "/utils/context.js"
import "focus-visible/dist/focus-visible"
import { Box, HStack, Image, Link, Modal, ModalBody, ModalContent, ModalHeader, ModalOverlay, Spacer, Text, VStack } from "@chakra-ui/react"
import { getEventURL } from "/utils/state.js"
import NextLink from "next/link"
import NextHead from "next/head"



export default function Component() {
  const state = useContext(StateContext)
  const router = useRouter()
  const [ colorMode, toggleColorMode ] = useContext(ColorModeContext)
  const focusRef = useRef();
  
  // Main event loop.
  const [addEvents, connectError] = useContext(EventLoopContext)

  // Set focus to the specified element.
  useEffect(() => {
    if (focusRef.current) {
      focusRef.current.focus();
    }
  })

  // Route after the initial page hydration.
  useEffect(() => {
    const change_complete = () => addEvents(initialEvents())
    router.events.on('routeChangeComplete', change_complete)
    return () => {
      router.events.off('routeChangeComplete', change_complete)
    }
  }, [router])


  return (
    <Fragment>
  <Fragment>
  {isTrue(connectError !== null) ? (
  <Fragment>
  <Modal isOpen={connectError !== null}>
  <ModalOverlay>
  <ModalContent>
  <ModalHeader>
  {`Connection Error`}
</ModalHeader>
  <ModalBody>
  <Text>
  {`Cannot connect to server: `}
  {(connectError !== null) ? connectError.message : ''}
  {`. Check if server is reachable at `}
  {getEventURL().href}
</Text>
</ModalBody>
</ModalContent>
</ModalOverlay>
</Modal>
</Fragment>
) : (
  <Fragment/>
)}
</Fragment>
  <HStack alignItems={`flex-start`} sx={{"transition": "left 0.5s, width 0.5s", "position": "relative"}}>
  <Box sx={{"display": ["none", "none", "block"], "minWidth": "20em", "height": "100%", "position": "sticky", "top": "0px", "borderRight": "4px solid black"}}>
  <VStack sx={{"height": "100dvh"}}>
  <HStack sx={{"width": "100%", "borderBottom": "4px solid black", "padding": "0", "borderWidth": "medium", "borderRadius": "3px", "borderColor": "pink", "margin": "3%"}}>
  <Box>
  <Box>
  <Image src={`/logo2.png`} sx={{"height": "3em", "marginLeft": "4%"}}/>
</Box>
</Box>
</HStack>
  <VStack alignItems={`flex-start`} sx={{"width": "100%", "overflowY": "auto", "padding": "1em"}}>
  <Link as={NextLink} href={`/`} sx={{"_hover": {"text-decoration": "none"}, "width": "100%"}}>
  <HStack sx={{"bg": isTrue((state.router.page.path === "/home") || (((state.router.page.path === "/") && "Home") === "Home")) ? `teal` : `rgb(21,24,51)`, "_hover": {"color": "hotpink"}, "color": isTrue((state.router.page.path === "/home") || (((state.router.page.path === "/") && "Home") === "Home")) ? `white` : `white`, "borderRadius": "0.375rem", "boxShadow": "0px 0px 0px 1px rgba(23, 25, 45, 1)", "width": "100%", "paddingX": "1em"}}>
  <Image src={`/github.svg`} sx={{"height": "2.5em", "padding": "0.5em"}}/>
  <Text>
  {`Home`}
</Text>
</HStack>
</Link>
  <Link as={NextLink} href={`/a-example`} sx={{"_hover": {"text-decoration": "none"}, "width": "100%"}}>
  <HStack sx={{"bg": isTrue((state.router.page.path === "/a-example") || (((state.router.page.path === "/") && "A-Example") === "Home")) ? `teal` : `rgb(21,24,51)`, "_hover": {"color": "hotpink"}, "color": isTrue((state.router.page.path === "/a-example") || (((state.router.page.path === "/") && "A-Example") === "Home")) ? `white` : `white`, "borderRadius": "0.375rem", "boxShadow": "0px 0px 0px 1px rgba(23, 25, 45, 1)", "width": "100%", "paddingX": "1em"}}>
  <Image src={`/github.svg`} sx={{"height": "2.5em", "padding": "0.5em"}}/>
  <Text>
  {`A-Example`}
</Text>
</HStack>
</Link>
  <Link as={NextLink} href={`/crypto1`} sx={{"_hover": {"text-decoration": "none"}, "width": "100%"}}>
  <HStack sx={{"bg": isTrue((state.router.page.path === "/crypto1") || (((state.router.page.path === "/") && "Crypto1") === "Home")) ? `teal` : `rgb(21,24,51)`, "_hover": {"color": "hotpink"}, "color": isTrue((state.router.page.path === "/crypto1") || (((state.router.page.path === "/") && "Crypto1") === "Home")) ? `white` : `white`, "borderRadius": "0.375rem", "boxShadow": "0px 0px 0px 1px rgba(23, 25, 45, 1)", "width": "100%", "paddingX": "1em"}}>
  <Image src={`/github.svg`} sx={{"height": "2.5em", "padding": "0.5em"}}/>
  <Text>
  {`Crypto1`}
</Text>
</HStack>
</Link>
  <Link as={NextLink} href={`/crypto2`} sx={{"_hover": {"text-decoration": "none"}, "width": "100%"}}>
  <HStack sx={{"bg": isTrue((state.router.page.path === "/crypto2") || (((state.router.page.path === "/") && "Crypto2") === "Home")) ? `teal` : `rgb(21,24,51)`, "_hover": {"color": "hotpink"}, "color": isTrue((state.router.page.path === "/crypto2") || (((state.router.page.path === "/") && "Crypto2") === "Home")) ? `white` : `white`, "borderRadius": "0.375rem", "boxShadow": "0px 0px 0px 1px rgba(23, 25, 45, 1)", "width": "100%", "paddingX": "1em"}}>
  <Image src={`/github.svg`} sx={{"height": "2.5em", "padding": "0.5em"}}/>
  <Text>
  {`Crypto2`}
</Text>
</HStack>
</Link>
  <Link as={NextLink} href={`/crypto3`} sx={{"_hover": {"text-decoration": "none"}, "width": "100%"}}>
  <HStack sx={{"bg": isTrue((state.router.page.path === "/crypto3") || (((state.router.page.path === "/") && "Crypto3") === "Home")) ? `teal` : `rgb(21,24,51)`, "_hover": {"color": "hotpink"}, "color": isTrue((state.router.page.path === "/crypto3") || (((state.router.page.path === "/") && "Crypto3") === "Home")) ? `white` : `white`, "borderRadius": "0.375rem", "boxShadow": "0px 0px 0px 1px rgba(23, 25, 45, 1)", "width": "100%", "paddingX": "1em"}}>
  <Image src={`/github.svg`} sx={{"height": "2.5em", "padding": "0.5em"}}/>
  <Text>
  {`Crypto3`}
</Text>
</HStack>
</Link>
  <Link as
[truncated — 2492 more characters]
```

### quicktest.py

```python
import cv2

# initialize the video camera (use 0 for the default camera)
cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('tradevid.mp4', fourcc, 30.0, (640, 480))

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Write the frame into the file 'output.mp4'
    out.write(frame)

    # Display the resulting frame
    cv2.imshow('Frame', frame)

    # Stop recording when 'q' key is pressed
    if cv2.waitKey(1) & 0xFF == 27:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
```

### facial_expressions.py

```python
import numpy as np
import pandas as pd
import random

import json

from hume import HumeBatchClient
from hume.models.config import FaceConfig

import cv2
import datetime

from antitilt import insert_into_table

API_KEY = # Insert API key here

all_emotions = ['Admiration', 'Adoration','Aesthetic Appreciation','Amusement','Anger','Anxiety','Awe','Awkwardness',
                'Boredom','Calmness','Concentration','Confusion','Contemplation','Contempt','Contentment','Craving',
                'Desire','Determination','Disappointment','Disgust','Distress','Doubt','Ecstasy','Embarrassment',
                'Empathic Pain','Entrancement','Envy','Excitement','Fear','Guilt','Horror','Interest',
                'Joy','Love','Nostalgia','Pain','Pride','Realization','Relief','Romance',
                'Sadness','Satisfaction','Shame','Surprise (negative)','Surprise (positive)','Sympathy','Tiredness','Triumph']

# Start webcam
print("\nStarting webcam.")
webcam = cv2.VideoCapture(0)
print("Press \'esc\' upon finalizing trade.\n")

fourcc = cv2.VideoWriter_fourcc('m','p','4','v')
out = cv2.VideoWriter('tradefootage.mp4', fourcc, 30.0, (640, 480)) # 30 fps, 640 x 480 px

while(True):
    # Capture frame
    check, frame = webcam.read()

    # Check for successful capture
    if check:
        # Write the frame into the file 'tradefootage.mp4'
        out.write(frame)
        # Display the resulting frame
        cv2.imshow("Midas", frame)

    # Stop recording when 'esc' key is pressed
    if cv2.waitKey(1) & 0xFF == 27:
        time_of_trade = datetime.datetime.now()
        currency = np.random.choice(['BTCUSDT', 'ETHUSDT', 'XRPUSDT', 'DOGEUSDT'])
        break

# Close webcam, release video, and free memory
webcam.release()
out.release()
cv2.destroyAllWindows()

# Start Hume Batch API
batch_client = HumeBatchClient(API_KEY)

# Send video to analyze facial expressions
job = batch_client.submit_job(urls=[], configs=[FaceConfig(identify_faces=True)], files=["tradefootage.mp4"])
print("Hume API is processing the footage...")
details = job.await_complete()
print("Emotion predictions downloaded.\n")
job.download_predictions("trade_emotions.json")

# Process emotion predictions into pandas DataFrame
vid_dict = json.load(open("trade_emotions.json"))[0]["results"]["predictions"][0]["models"]["face"]["grouped_predictions"][0]["predictions"]
trade_df = pd.DataFrame.from_dict({"name": all_emotions, "score": np.repeat(0.0, 48),
                                "top count": np.repeat(0, 48), "total top score": np.repeat(0.0, 48)})
num_frames = len(vid_dict)
for i in range(num_frames):
    emotions_dict = vid_dict[i]["emotions"]
    emotions_df = pd.DataFrame.from_dict(emotions_dict).sort_values("name")
    trade_df["score"] = trade_df["score"] + emotions_df["score"]

    emotions_df = emotions_df.sort_values("score", ascending=False)
    index = emotions_df.iloc[[0]].index[0]
    trade_df.iloc[index, 2] += 1
    trade_df.iloc[index, 3] += emotions_df.iloc[0, 1]
trade_df["score"] = trade_df["score"] / num_frames
trade_df.rename(columns={"score": "mean score"}, inplace=True)
trade_df["mean top score"] = (trade_df["total top score"] / trade_df["top count"]).fillna(0.0)

# Define statistics
highest_mean = trade_df.sort_values("mean score", ascending=False).iloc[0, 0], trade_df.sort_values("mean score", ascending=False).iloc[0, 1]
top = trade_df[trade_df["top count"] > 0].sort_values("top count", ascending=False)
top_emotion = top.iloc[0, 0]
top_emotion_time_proportion = top.iloc[0, 2] / num_frames
top_emotion_mean_score = round(top.iloc[0, 4], 2)

# Decide on descriptive message depending on emotion score
description = ""
percentage = round(top_emotion_time_proportion * 100, 1)

if top_emotion_mean_score >= 0.75 and top_emotion_mean_score <= 1:
    description = f"This trade was characterized by very prominent {top_emotion}, which was observed during {percentage}% of the time elapsed with a mean expressiveness score of {top_emotion_mean_score}."
elif top_emotion_mean_score >= 0.5 and top_emotion_mean_score < 0.75:
    description = f"{top_emotion} was fairly noticeable during {percentage}% of the time elapsed for this trade with a mean expressiveness score of {top_emotion_mean_score}."
elif top_emotion_mean_score >= 0.3 and top_emotion_mean_score < 0.5:
    description = f"Some {top_emotion} was detected during {percentage}% of the time elapsed for this trade with a mean expressiveness score of {top_emotion_mean_score}."
elif top_emotion_mean_score < 0.3:
    description = "This trade had no significant emotional context."

# Test printing
# print(top)
# print(f"Using mean over entire vid: {highest_mean}")
print(description, "\n")

# Send trade data to database
insert_into_table(currency, top_emotion , top_emotion_mean_score, np.round(random.random(), decimals=2), description, time_of_trade)
```

### antitilt.py

```python
import json 
import psycopg2
from psycopg2 import sql 
import datetime 
import mindsdb_sdk
import time
import pandas as pd
import numpy as np 
import matplotlib.pyplot as plt
import random



connection_params = {
    'database': 'Midas', 
    'user': 'postgres',
    'password' : 'password', 
    'host' : '6.tcp.us-cal-1.ngrok.io',
    'port' : 16376
}

all_emotions = ['Admiration', 'Adoration','Aesthetic Appreciation','Amusement','Anger','Anxiety','Awe','Awkwardness',
                'Boredom','Calmness','Concentration','Confusion','Contemplation','Contempt','Contentment','Craving',
                'Desire','Determination','Disappointment','Disgust','Distress','Doubt','Ecstasy','Embarrassment',
                'Empathic Pain','Entrancement','Envy','Excitement','Fear','Guilt','Horror','Interest',
                'Joy','Love','Nostalgia','Pain','Pride','Realization','Relief','Romance',
                'Sadness','Satisfaction','Shame','Surprise (negative)','Surprise (positive)','Sympathy','Tiredness','Triumph']

main_table = "Golden_Touch"
#server = mindsdb_sdk.connect(url='https://cloud.mindsdb.com/account', login='adithgang@gmail.com', password='Awesome#0725!')

dt = datetime

currencies = ['BTCUSDT', 'ETHUSDT', 'XRPUSDT', 'DOGEUSDT']

dataframes  = {currency : None for currency in currencies}


def create_crypto_tables():
    try:
        # Establish a connection to the PostgreSQL server
        conn = psycopg2.connect(
            **connection_params
        )

        # Create a cursor
        cursor = conn.cursor()

        # List of cryptocurrencies to create tables for
        currencies

        
        create_table_query = f'''
        CREATE TABLE IF NOT EXISTS {main_table} (
            currency VARCHAR(50),
            emotion VARCHAR(50),
            weight FLOAT,
            time_of_trade timestamp PRIMARY KEY,
            category VARCHAR(200),
            delta VARCHAR(200)
        );
        '''
        cursor.execute(create_table_query)
        print("Table created successfully.")

        # Commit the changes
        conn.commit()

        # Close the cursor and connection
        cursor.close()
        conn.close()

    except (Exception, psycopg2.Error) as error:
        print("Error while connecting to PostgreSQL", error)


def filter_table_by_emotion(emotion_name, currency):
    try:
        # Establish a connection to the PostgreSQL server
        conn = psycopg2.connect(
            **connection_params
        )

        # Create a cursor
        cursor = conn.cursor()

        # SQL query to fetch records filtered by emotion
        filter_query = f"SELECT * FROM {main_table} WHERE emotion = %s"
        cursor.execute(filter_query, (emotion_name, ))

        # Fetch all records with the specified emotion in the 'emotions' column
        filtered_data = cursor.fetchall()

        # Print or process the filtered data
        if filtered_data:
            print(f"Records with emotion '{emotion_name}':")
            for row in filtered_data:
                print(row)
            return filtered_data
        else:
            print(f"No records found with emotion '{emotion_name}'")

        # Close the cursor and connection
        cursor.close()
        conn.close()

    except (Exception, psycopg2.Error) as error:
        print("Error while connecting to PostgreSQL", error)
    

def drop_all_tables():
    try:
        # Establish a connection to the PostgreSQL server
        conn = psycopg2.connect(
        **connection_params
    )

        # Create a cursor
        cursor = conn.cursor()

        # SQL query to retrieve all table names
        get_table_names_query = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE';"
        cursor.execute(get_table_names_query)
        
        # Fetch all table names
        tables = cursor.fetchall()

        # Drop each table
        for table in tables:
            drop_table_query = f"DROP TABLE {table[0]} CASCADE;"
            cursor.execute(drop_table_query)
            print(f"Dropped table: {table[0]}")

        # Commit the changes
        conn.commit()

        # Close the cursor and connection
        cursor.close()
        conn.close()

    except (Exception, psycopg2.Error) as error:
        print("Error while connecting to PostgreSQL", error)
            
def get_crypto(crypto_name):
    try: 
        conn = psycopg2.connect(
            **connection_params
        )
        
        cursor = conn.cursor()
    except (Exception, psycopg2.Error) as error:
        print("Error while connecting to PostgreSQL", error)
        
def insert_into_table(currency, emotion, weight, delta, category, time=None):
    try:
        # Establish a connection to the PostgreSQL server
        conn = psycopg2.connect(
            **connection_params
        )

        # Create a cursor
        cursor = conn.cursor()

        if time == None:
            time = datetime.datetime.now()

        # SQL query to insert values into the specified table
        insert_query = f"INSERT INTO {main_table} (currency, emotion, weight, time_of_trade, category, delta) VALUES (%s, %s, %s, %s, %s, %s);"
        cursor.execute(insert_query, (currency, emotion, weight, time.strftime(f'%Y-%m-%d %H:%M:%S.%f'), category, delta))

        # Commit the changes
        conn.commit()
        print(f"Values inserted into the database successfully at {time}.\n")

        # Close the cursor and connection
        cursor.close()
        conn.close()

    except (Exception, psycopg2.Error) as error:
        print("Error while connecting to PostgreSQL", error)
        
        
def to_df():
    conn = psycopg2.connect(
        **connection_params
    )
    
    for curr in currencies:
        query = f"SELECT * FROM {main_table};"
        dataframes[curr] = pd.read_sql_query(query, conn, parse_dates=['datetime'])

def create_dummy_data(int_val):
    for curr in currencies:
        for i in range(25):
   
[truncated — 1293 more characters]
```

### webcamHume.py

```python
{'face': {'predictions': [{'frame': 0, 'time': None, 'bbox': {'x': 79.8251953125, 'y': 145.63632202148438, 'w': 66.31932067871094, 'h': 93.99874877929688}, 'prob': 0.9997592568397522, 'face_id': 'face_0', 'emotions': [{'name': 'Admiration', 'score': 0.13822343945503235}, {'name': 'Adoration', 'score': 0.0968332290649414}, {'name': 'Aesthetic Appreciation', 'score': 0.08996476233005524}, {'name': 'Amusement', 'score': 0.12080354243516922}, {'name': 'Anger', 'score': 0.08223163336515427}, {'name': 'Anxiety', 'score': 0.13870172202587128}, {'name': 'Awe', 'score': 0.09909701347351074}, {'name': 'Awkwardness', 'score': 0.179997518658638}, {'name': 'Boredom', 'score': 0.4692903161048889}, {'name': 'Calmness', 'score': 0.5371012091636658}, {'name': 'Concentration', 'score': 0.5091250538825989}, {'name': 'Contemplation', 'score': 0.3228100836277008}, {'name': 'Confusion', 'score': 0.3623392581939697}, {'name': 'Contempt', 'score': 0.21809905767440796}, {'name': 'Contentment', 'score': 0.15656062960624695}, {'name': 'Craving', 'score': 0.061851076781749725}, {'name': 'Determination', 'score': 0.16024073958396912}, {'name': 'Disappointment', 'score': 0.30437418818473816}, {'name': 'Disgust', 'score': 0.07417300343513489}, {'name': 'Distress', 'score': 0.16074883937835693}, {'name': 'Doubt', 'score': 0.3738574683666229}, {'name': 'Ecstasy', 'score': 0.027744388207793236}, {'name': 'Embarrassment', 'score': 0.07689277827739716}, {'name': 'Empathic Pain', 'score': 0.07653436064720154}, {'name': 'Entrancement', 'score': 0.15042324364185333}, {'name': 'Envy', 'score': 0.06305161118507385}, {'name': 'Excitement', 'score': 0.05196203663945198}, {'name': 'Fear', 'score': 0.08703615516424179}, {'name': 'Guilt', 'score': 0.07454301416873932}, {'name': 'Horror', 'score': 0.03175753355026245}, {'name': 'Interest', 'score': 0.3339443802833557}, {'name': 'Joy', 'score': 0.0794900581240654}, {'name': 'Love', 'score': 0.09560509771108627}, {'name': 'Nostalgia', 'score': 0.09587942808866501}, {'name': 'Pain', 'score': 0.08922010660171509}, {'name': 'Pride', 'score': 0.09816807508468628}, {'name': 'Realization', 'score': 0.17592090368270874}, {'name': 'Relief', 'score': 0.0770576074719429}, {'name': 'Romance', 'score': 0.04691740870475769}, {'name': 'Sadness', 'score': 0.2273048609495163}, {'name': 'Satisfaction', 'score': 0.12783396244049072}, {'name': 'Desire', 'score': 0.049760930240154266}, {'name': 'Shame', 'score': 0.061700060963630676}, {'name': 'Surprise (negative)', 'score': 0.039832860231399536}, {'name': 'Surprise (positive)', 'score': 0.03357018157839775}, {'name': 'Sympathy', 'score': 0.07145748287439346}, {'name': 'Tiredness', 'score': 0.2223949134349823}, {'name': 'Triumph', 'score': 0.036787137389183044}]}, {'frame': 0, 'time': None, 'bbox': {'x': 333.1047058105469, 'y': 29.607683181762695, 'w': 63.851806640625, 'h': 88.50285148620605}, 'prob': 0.9998762607574463, 'face_id': 'face_1', 'emotions': [{'name': 'Admiration', 'score': 0.09663747251033783}, {'name': 'Adoration', 'score': 0.06478017568588257}, {'name': 'Aesthetic Appreciation', 'score': 0.07582148909568787}, {'name': 'Amusement', 'score': 0.09386230260133743}, {'name': 'Anger', 'score': 0.08977226912975311}, {'name': 'Anxiety', 'score': 0.14645130932331085}, {'name': 'Awe', 'score': 0.07924811542034149}, {'name': 'Awkwardness', 'score': 0.1874396950006485}, {'name': 'Boredom', 'score': 0.6420041918754578}, {'name': 'Calmness', 'score': 0.6627218723297119}, {'name': 'Concentration', 'score': 0.5748749375343323}, {'name': 'Contemplation', 'score': 0.2696967124938965}, {'name': 'Confusion', 'score': 0.34081557393074036}, {'name': 'Contempt', 'score': 0.21107876300811768}, {'name': 'Contentment', 'score': 0.14650239050388336}, {'name': 'Craving', 'score': 0.05472566932439804}, {'name': 'Determination', 'score': 0.1601105034351349}, {'name': 'Disappointment', 'score': 0.32196518778800964}, {'name': 'Disgust', 'score': 0.07915512472391129}, {'name': 'Distress', 'score': 0.1648070514202118}, {'name': 'Doubt', 'score': 0.3291372060775757}, {'name': 'Ecstasy', 'score': 0.023200923576951027}, {'name': 'Embarrassment', 'score': 0.07593193650245667}, {'name': 'Empathic Pain', 'score': 0.08076656609773636}, {'name': 'Entrancement', 'score': 0.14792987704277039}, {'name': 'Envy', 'score': 0.05691107362508774}, {'name': 'Excitement', 'score': 0.039750270545482635}, {'name': 'Fear', 'score': 0.08419451117515564}, {'name': 'Guilt', 'score': 0.07869042456150055}, {'name': 'Horror', 'score': 0.03124850243330002}, {'name': 'Interest', 'score': 0.30683663487434387}, {'name': 'Joy', 'score': 0.0611255019903183}, {'name': 'Love', 'score': 0.0700378268957138}, {'name': 'Nostalgia', 'score': 0.08101440221071243}, {'name': 'Pain', 'score': 0.09248560667037964}, {'name': 'Pride', 'score': 0.07608599215745926}, {'name': 'Realization', 'score': 0.14838743209838867}, {'name': 'Relief', 'score': 0.06704279035329819}, {'name': 'Romance', 'score': 0.037265948951244354}, {'name': 'Sadness', 'score': 0.2574552893638611}, {'name': 'Satisfaction', 'score': 0.10626983642578125}, {'name': 'Desire', 'score': 0.04592376574873924}, {'name': 'Shame', 'score': 0.06504105031490326}, {'name': 'Surprise (negative)', 'score': 0.04297386482357979}, {'name': 'Surprise (positive)', 'score': 0.03181309252977371}, {'name': 'Sympathy', 'score': 0.07221651822328568}, {'name': 'Tiredness', 'score': 0.30068400502204895}, {'name': 'Triumph', 'score': 0.02655092440545559}]}, {'frame': 0, 'time': None, 'bbox': {'x': 742.9522705078125, 'y': 152.49847412109375, 'w': 63.271728515625, 'h': 85.35723876953125}, 'prob': 0.9999767541885376, 'face_id': 'face_2', 'emotions': [{'name': 'Admiration', 'score': 0.10695216059684753}, {'name': 'Adoration', 'score': 0.06982997804880142}, {'name': 'Aesthetic Appreciation', 'score': 0.07627788186073303}, {'name': 'Amusement', 'score': 0.14079315960407257}, {'name': 'Anger', 'score': 0.08649491518735886}, {'name': 'Anxiety', 'score': 0.14813803136348724}, {'name': 'Aw
[truncated — 4901 more characters]
```

### website/rxconfig.py

```python
import reflex as rx

config = rx.Config(
    app_name="website",
)
```

### website/Miscalgos.sql

```sql

CREATE DATABASE Dummy
WITH ENGINE = "postgres",
PARAMETERS = {
  "user": "postgres",
  "port": 10392,
  "password": "password",
  "host": "4.tcp.us-cal-1.ngrok.io",
  "database": "Midas"
  -- Other parameters --
  };

-- model to pull data from binance based off the time of a trade
CREATE JOB binance_data AS (
    SELECT *
    FROM my_binance.aggregated_trade_data AS trade
    JOIN Hume.crypto_trades  AS crypto_data
    ON trade.symbol = crypto_data.crypto
    LIMIT 10
);
END '2024-02-01 00:00:00'
EVERY 1/2 day;


-- model to give advice based off the emotion weights and crypto

CREATE MODEL candlelit
PREDICT advice
USING
  engine = 'openai',
  max_tokens = 300,
  temperature = 0.75,
  api_key = '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',
  model_name = 'gpt-4', -- you can also use 'text-davinci-003' or 'gpt-3.5-turbo'
  prompt_template = '

Your are a stock advice bot, your name is midas and you are helping people with their questions answer very spartan.

For user emotion tracking: {{emotion_sigfig_and_emotionweight}}\

and for user trade tracking: {{crypto_and_change}}\

In less than 200 characters, generate advice using the emotion and extent of the emotion as well as the crypto currency invested in and how the trade did. Advise them to invest more if the emotion led to a positive trade, and advise them to stay away from trades when feeling a certain emotion if the trade did poorly.';
-

-- CREATE MODEL mindsdb.emotions_crypto_predictor
-- FROM my_binance,Hume
-- WHERE emotions IS NOT NULL AND crypto_trades IS NOT NULL
-- PREDICT crypto_trades
-- USING engine = 'lightwood',
--       tag = 'emotions crypto trade model';


-- CREATE MODEL EmotionToTrade
-- FROM my_binance,Hume (
--   SELECT * FROM aggregated_trade_data,Emotions
--   WHERE symbol = crypto_data.crypto
--   )
-- PREDICT open_price
-- ORDER BY open_time
-- GROUP BY [group_by];


```

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