Last active
January 28, 2024 07:19
-
-
Save graylan0/bab627e09cb0166b5eac748701ef1e8a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import aiosqlite | |
import asyncio | |
from datetime import datetime | |
from markdown2 import markdown | |
from kivymd.app import MDApp | |
from kivymd.uix.screen import MDScreen | |
from kivymd.uix.button import MDRaisedButton | |
from kivymd.uix.boxlayout import MDBoxLayout | |
from kivy.uix.image import AsyncImage | |
from kivy.clock import Clock | |
from kivymd.uix.textfield import MDTextField | |
from kivy.uix.label import Label | |
import numpy as np | |
import pennylane as qml | |
import requests | |
import json | |
import httpx | |
import base64 | |
import logging | |
DATABASE_NAME = "mental_health.db" | |
CONFIG_FILE = 'configopenai.json' | |
with open(CONFIG_FILE, 'r') as f: | |
config = json.load(f) | |
openai_api_key = config['openai_api_key'] | |
stable_url = config['stable_url'] | |
logging.basicConfig(level=logging.INFO) | |
num_qubits = 6 | |
dev = qml.device('default.qubit', wires=num_qubits) | |
@qml.qnode(dev) | |
def quantum_circuit(color_code, datetime_factor): | |
r, g, b = [int(color_code[i:i+2], 16) for i in (1, 3, 5)] | |
r, g, b = r / 255.0, g / 255.0, b / 255.0 | |
qml.RY(r * np.pi, wires=0) | |
qml.RY(g * np.pi, wires=1) | |
qml.RY(b * np.pi, wires=2) | |
qml.RY(datetime_factor * np.pi, wires=3) | |
qml.CNOT(wires=[0, 1]) | |
qml.CNOT(wires=[1, 2]) | |
qml.CNOT(wires=[2, 3]) | |
return qml.state() | |
def mixed_state_to_color_code(mixed_state): | |
mixed_state = np.array(mixed_state) | |
probabilities = np.abs(mixed_state)**2 | |
probabilities /= np.sum(probabilities) | |
r_prob = probabilities[:len(probabilities)//3] | |
g_prob = probabilities[len(probabilities)//3:2*len(probabilities)//3] | |
b_prob = probabilities[2*len(probabilities)//3:] | |
r = int(np.sum(r_prob) * 255) | |
g = int(np.sum(g_prob) * 255) | |
b = int(np.sum(b_prob) * 255) | |
return f'#{r:02x}{g:02x}{b:02x}' | |
async def initialize_database(): | |
async with aiosqlite.connect(DATABASE_NAME) as db: | |
await db.execute('''CREATE TABLE IF NOT EXISTS mood_entries ( | |
id INTEGER PRIMARY KEY, | |
mood_text TEXT, | |
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''') | |
await db.commit() | |
class QuantumImageApp(MDApp): | |
def __init__(self, **kwargs): | |
super().__init__(**kwargs) | |
self.theme_cls.theme_style = "Dark" | |
self.theme_cls.primary_palette = "BlueGray" | |
self.root = MDScreen() | |
self.image_display = AsyncImage(source="") | |
self.create_gui() | |
def create_gui(self): | |
self.layout = MDBoxLayout(orientation="vertical", md_bg_color=[0, 0, 0, 1]) | |
self.text_box = MDTextField(hint_text="Enter your mood", hint_text_color=[1, 1, 1, 1]) | |
self.journal_text_box = MDTextField(hint_text="Enter journal text", hint_text_color=[1, 1, 1, 1], multiline=True) | |
self.checkout_time_picker = MDTextField(hint_text="Enter checkout time (YYYY-MM-DD HH:MM)", hint_text_color=[1, 1, 1, 1]) | |
run_button = MDRaisedButton(text="Generate Visual", on_press=lambda x: asyncio.run(self.generate_visual(x)), text_color=[1, 1, 1, 1]) | |
self.image_display = AsyncImage(source="", allow_stretch=True, keep_ratio=True) | |
self.image_display.size_hint_y = None | |
self.image_display.height = 0 | |
self.layout.add_widget(self.text_box) | |
self.layout.add_widget(self.journal_text_box) | |
self.layout.add_widget(self.checkout_time_picker) | |
self.layout.add_widget(run_button) | |
self.layout.add_widget(self.image_display) | |
self.root.add_widget(self.layout) | |
async def generate_visual(self, instance): | |
mood_text = self.text_box.text | |
journal_text = self.journal_text_box.text | |
checkout_time_str = self.checkout_time_picker.text | |
await asyncio.ensure_future(self.process_mood_journal_and_time(mood_text, journal_text, checkout_time_str)) | |
async def process_mood_journal_and_time(self, mood_text, journal_text, checkout_time_str): | |
await self.save_mood_entry(mood_text) | |
gpt4_analysis = await self.analyze_journal_and_provide_trading_advice(journal_text, mood_text) | |
mood_fluctuation_report = await self.analyze_mood_fluctuations() | |
markdown_report = self.generate_markdown_report(gpt4_analysis, mood_fluctuation_report) | |
Clock.schedule_once(lambda dt: self.display_markdown_report(markdown_report)) | |
color_code, datetime_factor = await self.map_sentiment_to_color(mood_text) | |
quantum_state = quantum_circuit(color_code, datetime_factor) | |
image_path = await self.generate_image_from_quantum_data(quantum_state) | |
if image_path: | |
self.update_image(image_path) | |
async def save_mood_entry(self, mood_text): | |
async with aiosqlite.connect(DATABASE_NAME) as db: | |
await db.execute('''INSERT INTO mood_entries (mood_text) VALUES (?)''', (mood_text,)) | |
await db.commit() | |
async def analyze_journal_and_provide_trading_advice(self, journal_text, mood_text): | |
prompt = ( | |
f"Consider the following journal entry and the user's mood: '{mood_text}'.\n\n" | |
"Journal Entry:\n" | |
f"{journal_text}\n\n" | |
"Based on this, provide a detailed analysis of the user's emotional state over time. " | |
"Include insights into any patterns or changes in sentiment, potential reasons behind these changes, " | |
"and suggestions for topics the user might find beneficial to explore in future journal entries. " | |
"Additionally, based on the user's emotional patterns and interests, suggest ideas or strategies " | |
"that could improve their capability to trade in economic markets, focusing on areas such as risk management, " | |
"market analysis, and decision-making under pressure." | |
) | |
async with httpx.AsyncClient() as client: | |
response = await client.post( | |
"https://api.openai.com/v1/chat/completions", | |
headers={"Authorization": f"Bearer {openai_api_key}"}, | |
json={ | |
"model": "gpt-4", | |
"messages": [{"role": "system", "content": prompt}] | |
} | |
) | |
response.raise_for_status() | |
result = response.json() | |
return result['choices'][0]['message']['content'].strip() | |
def generate_markdown_report(self, gpt4_analysis, mood_fluctuation_report): | |
report = f""" | |
# Comprehensive Emotional Analysis Report | |
## GPT-4 Sentiment Analysis | |
{gpt4_analysis} | |
## Mood Fluctuation Overview | |
{mood_fluctuation_report} | |
### Insights and Recommendations | |
Based on the analysis above, it is evident that the user's emotional state shows [specific patterns/changes]. | |
It may be beneficial for the user to explore topics such as [suggested topics] in their future journaling | |
to further understand and manage their emotional well-being. | |
_This report is generated based on advanced AI analysis of journal entries and mood data._ | |
""" | |
return markdown(report) | |
def display_markdown_report(self, markdown_report): | |
report_label = Label(text=markdown_report, markup=True) | |
self.layout.add_widget(report_label) | |
async def map_sentiment_to_color(self, sentiment): | |
async with httpx.AsyncClient() as client: | |
response = await client.post( | |
"https://api.openai.com/v1/chat/completions", | |
headers={"Authorization": f"Bearer {openai_api_key}"}, | |
json={ | |
"model": "gpt-4", | |
"messages": [ | |
{"role": "system", "content": "Suggest a color based on the following sentiment."}, | |
{"role": "user", "content": sentiment} | |
] | |
} | |
) | |
response.raise_for_status() | |
result = response.json() | |
color_suggestion = result['choices'][0]['message']['content'].strip() | |
return color_suggestion if color_suggestion else "#808080", 1 | |
async def generate_image_from_quantum_data(self, quantum_state): | |
color_code = mixed_state_to_color_code(quantum_state) | |
prompt = f"Generate an image with predominant color {color_code}" | |
url = stable_url | |
payload = { | |
"prompt": prompt, | |
"steps": 121, | |
"seed": random.randrange(sys.maxsize), | |
"enable_hr": "false", | |
"denoising_strength": "0.7", | |
"cfg_scale": "7", | |
"width": 666, | |
"height": 456, | |
"restore_faces": "true", | |
} | |
response = requests.post(url, json=payload) | |
response.raise_for_status() | |
r = response.json() | |
if 'images' in r and r['images']: | |
base64_data = r['images'][0] | |
image_bytes = base64.b64decode(base64_data) | |
image_path = f"output_{random.randint(0, 10000)}.png" | |
with open(image_path, "wb") as image_file: | |
image_file.write(image_bytes) | |
return image_path | |
else: | |
return None | |
def update_image(self, image_path): | |
if image_path and os.path.exists(image_path): | |
self.image_display.source = image_path | |
self.image_display.size_hint_y = 1 | |
self.image_display.height = 200 | |
else: | |
self.image_display.source = "" | |
self.image_display.size_hint_y = None | |
self.image_display.height = 0 | |
if __name__ == "__main__": | |
asyncio.run(initialize_database()) | |
QuantumImageApp().run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment