From a3ea23ebd7da7a6a6f95343fcd1cad0effd8e2e3 Mon Sep 17 00:00:00 2001 From: YasinOnm08 Date: Thu, 19 Sep 2024 16:52:16 +0200 Subject: [PATCH 01/10] Enter works again --- app/InputFrontend.tsx | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/app/InputFrontend.tsx b/app/InputFrontend.tsx index c3cdea8..cf9dffc 100644 --- a/app/InputFrontend.tsx +++ b/app/InputFrontend.tsx @@ -14,19 +14,28 @@ const InputFrontend = React.forwardRef( setInputValue(e.target.value); }; + const handleKeyDown = (event: React.KeyboardEvent) => { + if (event.key === 'Enter') { + onSendClick(inputValue); // Call the function passed via props + setInputValue(''); // Optionally clear input after submission + event.preventDefault(); // Prevent default action (e.g., form submission) + } + }; + return ( -
+
- -
From 7bf91cdf7eab1aaf55c328119fe0643b611610f0 Mon Sep 17 00:00:00 2001 From: Patrick_Pluto Date: Fri, 20 Sep 2024 09:03:46 +0200 Subject: [PATCH 02/10] backend changes --- .gitignore | 1 + py/.idea/.gitignore | 3 -- .../inspectionProfiles/profiles_settings.xml | 6 ---- py/.idea/misc.xml | 10 ------ py/.idea/modules.xml | 8 ----- py/.idea/py.iml | 13 ------- py/.idea/vcs.xml | 6 ---- py/__pycache__/ai.cpython-312.pyc | Bin 0 -> 1769 bytes py/ai.py | 32 ++++++++++++++++++ py/api.py | 18 +--------- py/requirements.txt | 3 +- 11 files changed, 36 insertions(+), 64 deletions(-) delete mode 100644 py/.idea/.gitignore delete mode 100644 py/.idea/inspectionProfiles/profiles_settings.xml delete mode 100644 py/.idea/misc.xml delete mode 100644 py/.idea/modules.xml delete mode 100644 py/.idea/py.iml delete mode 100644 py/.idea/vcs.xml create mode 100644 py/__pycache__/ai.cpython-312.pyc create mode 100644 py/ai.py diff --git a/.gitignore b/.gitignore index bb3b79a..ea5d9c5 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ venv/ key.pem cert.pem +api_key.txt diff --git a/py/.idea/.gitignore b/py/.idea/.gitignore deleted file mode 100644 index 26d3352..0000000 --- a/py/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml diff --git a/py/.idea/inspectionProfiles/profiles_settings.xml b/py/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 105ce2d..0000000 --- a/py/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/py/.idea/misc.xml b/py/.idea/misc.xml deleted file mode 100644 index 3671ece..0000000 --- a/py/.idea/misc.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/py/.idea/modules.xml b/py/.idea/modules.xml deleted file mode 100644 index 3a65488..0000000 --- a/py/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/py/.idea/py.iml b/py/.idea/py.iml deleted file mode 100644 index 49f4c24..0000000 --- a/py/.idea/py.iml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/py/.idea/vcs.xml b/py/.idea/vcs.xml deleted file mode 100644 index 6c0b863..0000000 --- a/py/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/py/__pycache__/ai.cpython-312.pyc b/py/__pycache__/ai.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..998a499725690d2957d619b87d4ab9b2bdfd3657 GIT binary patch literal 1769 zcmZvdOK2NM7=ZuTmt=WmNAfGN8yZsE>Ec&vsGty9lICSf4KBS{v@FZ+I@8 zWn|ie4?3g}Q>dF<>O&7L&Y?ZE$I?@vmxvfFrY#iOOAZCQ3K)FqKU%Gy9ZCQGGyiL6 z_xne`rqe0F(HQ(^;jswt7oWsKYAelgR5ri@i+E5Zc|y1@ctTzf;0{>g8d%bn5P9dt zilE6a_(UTt@xBv;)bM7_$QsGEE3^~akS7-81zWVp8f>*a^AgU5V{^G8Y7!H!&zSLz zanA()@W!F}4T=p230_*mjjO~9c&$Q}Si}-6(IHQyt#+POsVd!skFNr(%Ap*)S7l4S zfD=pMa;u$}Kvi&+*yre46_j#%=J}@Kt(?0) zGkIc#rwnuypTXamfsLW{p+iHdYxULRwe)L?O{@(s+rk=a~bETe}tE+R{>hzwBflVv{Cotia zTbL~1i#(1A$026-P2ecF-0#$gp>z-NIC6+>t1@;4e&TEdLJntZd@4T?V}w?fs^aq3 zaca1orxtL^fkjZ;D6b}}2?X^ff|^7O)&KE7!Z7J}owd8?&aOq6yVtBeFnTaBHmHbJ|2*X=`BXbnBlDS9%K4&l~)PAM1fqVGY=;=d$!Xf z-)0*90~-tL3ttpAO6#TP{iC%z`yzCWzEmK4VRK+Rqt%o@2QPg+_GoNpaJ)V^9yPo&QiLLr_Pecbye3tSu(t~MGZnDbj+e1 z7JQ5LV-h-y;ya)NT<4F7@`h*$t_1v_VhtK{W=}}TACRU9N_MxU?w&_=Pf+E2v>K^V zA|8szSjXY>j9xqEH_ESZ?Xc!S@>+DmZ__a}@RK><#$AyR@&{b}4buC{5dKg73tYAW F{{t)}g^>UN literal 0 HcmV?d00001 diff --git a/py/ai.py b/py/ai.py new file mode 100644 index 0000000..900b2ff --- /dev/null +++ b/py/ai.py @@ -0,0 +1,32 @@ +from mistralai import Mistral +import ollama + + +class AI: + @staticmethod + def process_local(model, messages, return_class, access_token): + stream = ollama.chat( + model=model, + messages=messages, + stream=True, + options={"temperature": 0.8}, + ) + + for chunk in stream: + print(chunk['message']['content']) + return_class.ai_response[access_token] += chunk['message']['content'] + + @staticmethod + def process_mistralai(model, messages, return_class, access_token): + with open("api_key.txt", 'r') as f: + api_key = f.read().strip() + + client = Mistral(api_key=api_key) + + stream_response = client.chat.stream( + model=model, + messages=messages + ) + + for chunk in stream_response: + return_class.ai_response[access_token] += chunk.data.choices[0].delta.content diff --git a/py/api.py b/py/api.py index 9cf2e63..b25e4d4 100644 --- a/py/api.py +++ b/py/api.py @@ -1,22 +1,7 @@ from flask import Flask, request, jsonify from flask_cors import CORS -import ollama import secrets - - -class AI: - @staticmethod - def process_local(model, messages, return_class, access_token): - stream = ollama.chat( - model=model, - messages=messages, - stream=True, - options={"temperature": 0}, - ) - - for chunk in stream: - print(chunk['message']['content']) - return_class.ai_response[access_token] += chunk['message']['content'] +from ai import AI class API: @@ -58,4 +43,3 @@ class API: if __name__ == '__main__': api = API() api.run() - diff --git a/py/requirements.txt b/py/requirements.txt index 1e95d6f..b4f811a 100644 --- a/py/requirements.txt +++ b/py/requirements.txt @@ -1,3 +1,4 @@ flask flask-cors -ollama \ No newline at end of file +ollama +mistralai \ No newline at end of file From eb8fef13ff126e002d31f4ce3f41e11579b4b142 Mon Sep 17 00:00:00 2001 From: Patrick_Pluto Date: Fri, 20 Sep 2024 09:17:00 +0200 Subject: [PATCH 03/10] Fixes. --- py/__pycache__/ai.cpython-312.pyc | Bin 1769 -> 1868 bytes py/ai.py | 4 ++++ 2 files changed, 4 insertions(+) diff --git a/py/__pycache__/ai.cpython-312.pyc b/py/__pycache__/ai.cpython-312.pyc index 998a499725690d2957d619b87d4ab9b2bdfd3657..ff29eb91dc4b3580658ed60b773323834ad4eae1 100644 GIT binary patch delta 537 zcmZWj&nrYx7`@+n_r7_LnMW978e>L=8cC8!e$`})@~bE`H8V9bGrDgk7GuRi$wJ>= zHb^%70Tf#ntki5RM5#eGR_>kGkbH}C&v(xKPUqQmYnnGMR|OF>+x(iKbkDqi>%H57 z@fgc1%TyYFC$A0)Ax}riLKh($EbA!yc^1>WVu?8ZN&?0l_%3#e1cubU``3Sizeyr*>*nY!FxS;(0H$RKDvFluS~-h zekd1BrK-+yjo;UaTN)&5~xYJiH!#tV1gqM>xi&+{KFjRYQ2l`aND^w%xf}zpP4;up5Z< zs@J_NGJ>D1uf`)J-YVdP@CM22aai*woNN+4RHD@s6-kSYg1#vxo3~Y)+6PQrg=xV^ uC9N!vu0)eul{r-sq{rJO*x7=8>4T|EEVmLL<{fyYd8-025AQ@`>C-ofq;IPL delta 479 zcmY+AJxgOz5Qb;&x##3V?-im+{0iCCs9dxN+boN^h1d(Lf(jzRBoK*F&W*S$5&wV| zVc0FUQm_&I3pU#-B36>cA7CLwQwS-Q0 z7kB|8oTM8Z=#-nfP%78jGKCeL^EWq2evSgx0j|(*Dqk)=@fA ziM_D=feisFQny&vyN!Ib+T~KK+LEmSzNu%|LhA*;tTV+-K?~mFGT74|qqW Date: Fri, 20 Sep 2024 09:17:28 +0200 Subject: [PATCH 04/10] convo with new prompts --- app/ConversationFrontend.tsx | 15 ++++++++---- app/InputOutputHandler.tsx | 43 +++++++++++++++++----------------- app/ProcessAPI.js | 45 +++++++++++++++++++++--------------- 3 files changed, 59 insertions(+), 44 deletions(-) diff --git a/app/ConversationFrontend.tsx b/app/ConversationFrontend.tsx index 80cf49b..00948db 100644 --- a/app/ConversationFrontend.tsx +++ b/app/ConversationFrontend.tsx @@ -1,7 +1,12 @@ import React, { ForwardedRef, useEffect, useRef } from 'react'; +type Message = { + role: string + content: string +} + interface ConversationProps { - messages: string[]; + messages: Message[]; onResendClick: () => void; onEditClick: () => void; onCopyClick: () => void; @@ -22,14 +27,16 @@ const ConversationFrontend = React.forwardRef
{messages.map((message, index) => { - const isUserMessage = message.startsWith('User:'); - console.log(messages) + let isUserMessage + if (message.role == "user") { + isUserMessage = message + } return (
-

{message}

+

{message.content}

); })} diff --git a/app/InputOutputHandler.tsx b/app/InputOutputHandler.tsx index 2bbe5b0..6f428dc 100644 --- a/app/InputOutputHandler.tsx +++ b/app/InputOutputHandler.tsx @@ -27,30 +27,31 @@ const handleCopyClick = () => { const InputOutputBackend: React.FC = () => { const [accessToken, setAccessToken] = useState("") const workerRef = useRef(null) + type Message = { + role: string + content: string + } + type SystemPrompt = { + + } - const handleSendClick = (message: string) => { - var system = "You give really short answers (maximum of 30 sentences). The following is the chat history." - for (let index = 0; index < messages.length; index++) { - system += messages[index] + " "; - }; + const handleSendClick = (message:string) => { + var system:Message = {role:"system" ,content:"You are a helpful assistant that gives short answers."} - HandlePostRequest(message, "phi3.5", system) - - addMessage('User: ' + message); + addMessage("user",message); + HandlePostRequest(messages, "phi3.5", system) }; const [messages, setMessages] = useState([ - 'User: Hello!', - 'AI: Hi there!', - 'User: How are you?', - 'AI: I’m good, thank you!' + { role:"assistant", content:'Hello. I\'m Your AI Virtual Assistant' } ]); - const addMessage = (message: string) => { - setMessages((prevMessages) => [...prevMessages, message]); + const addMessage = (role:string ,content: string) => { + setMessages((prevMessages) => [...prevMessages, {role,content}]); }; + useEffect(() => { workerRef.current = new Worker(new URL("./ProcessAPI.js", import.meta.url)) workerRef.current.postMessage({}) @@ -65,20 +66,20 @@ const InputOutputBackend: React.FC = () => { } },[]) - const HandleGetRequest = (message: string, ai_model: string, system_prompt: string) => { + const HandleGetRequest = (messages: Message[], ai_model: string, system_prompt: Message) => { if (workerRef.current) { - workerRef.current.postMessage({ functionName: "getResponse", access_token: accessToken, message: message, ai_model: ai_model, system_prompt: system_prompt }) + workerRef.current.postMessage({ functionName: "getResponse", access_token: accessToken, messages: messages, ai_model: ai_model, system_prompt: system_prompt }) workerRef.current.onmessage = (e) => { - addMessage("AI: " + e.data) + addMessage("assistant",e.data) } } } - const HandlePostRequest = (message: string, ai_model: string, system_prompt: string) => { + const HandlePostRequest = (messages: Message[], ai_model: string, system_prompt: Message) => { if (workerRef.current) { - workerRef.current.postMessage({ functionName: "postRequest", access_token: accessToken, message: message, ai_model: ai_model, system_prompt: system_prompt }) + workerRef.current.postMessage({ functionName: "postRequest", access_token: accessToken, messages: messages, ai_model: ai_model, system_prompt: system_prompt }) workerRef.current.onmessage = (e) => { - HandleGetRequest(message,ai_model,system_prompt) + HandleGetRequest(messages,ai_model,system_prompt) } } } @@ -97,7 +98,7 @@ const InputOutputBackend: React.FC = () => { onMicClick={handleMicClick} />
- ); + ) } export default InputOutputBackend diff --git a/app/ProcessAPI.js b/app/ProcessAPI.js index c161c62..0aaced7 100644 --- a/app/ProcessAPI.js +++ b/app/ProcessAPI.js @@ -1,32 +1,39 @@ import axios from 'axios' +import { type } from 'os'; onmessage = function (e) { - const { functionName = "getAccess", access_token = "", message = "", ai_model = "phi3.5", system_prompt = "You are a helpful assistant" } = e.data - const data = { - "ai_model": ai_model, - "message": message, - "system_prompt": system_prompt, - "access_token": access_token + const { functionName = "getAccess", access_token = "", messages = [], ai_model = "phi3.5", system_prompt = {role:"system" ,content: "You are a helpful assistant that gives short answers"}} = e.data + + + let data = { + ai_model: ai_model, + messages: messages, + access_token: access_token }; + console.log(messages) switch (functionName) { case "getAccess": - axios.get('https://127.0.0.1:5000/interstellar/api/ai_create') - .then(Response => { - postMessage(Response.data.access_token) - }).catch(error => { - console.error("Error with GET Token request:", error) - }) + console.log("getting access...") + axios.get('https://localhost:5000/interstellar/api/ai_create') + .then(Response => { + postMessage(Response.data.access_token) + }).catch(error => { + console.error("Error with GET Token request:", error) + }) break case "postRequest": - axios.post('https://127.0.0.1:5000/interstellar/api/ai_send', data) - .then(Response => { - postMessage(Response.data) - }).catch(error => { - console.error("Error:", error) - }) + messages.unshift(system_prompt) + console.log("sending...") + console.log(messages) + axios.post('https://localhost:5000/interstellar/api/ai_send', data) + .then(Response => { + postMessage(Response.data) + }).catch(error => { + console.error("Error:", error) + }) break case "getResponse": - axios.get('https://127.0.0.1:5000/interstellar/api/ai_get?access_token=' + access_token) + axios.get('https://localhost:5000/interstellar/api/ai_get?access_token=' + access_token) .then(Response => { postMessage(Response.data.response) }).catch(error => { From 31e37ecd824dd38b7220d3b8de1e1d00b34fec2e Mon Sep 17 00:00:00 2001 From: Patrick_Pluto Date: Fri, 20 Sep 2024 09:21:07 +0200 Subject: [PATCH 05/10] Debug. --- py/__pycache__/ai.cpython-312.pyc | Bin 1868 -> 1927 bytes py/ai.py | 5 ++++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/py/__pycache__/ai.cpython-312.pyc b/py/__pycache__/ai.cpython-312.pyc index ff29eb91dc4b3580658ed60b773323834ad4eae1..a1c10a8f80335103a3b77aa85e3690ddecdfa8d8 100644 GIT binary patch delta 355 zcmX@Z*Ury-nwOW00SH2r-lmyOkY~mSftr|ubhFD$(hFaDVR*)PH zdiYrwQdn!4ve+i`GAi=2A*o`UY|SXi$TpdWMHWaFGa9f%G(DKSiqT7ywV)_7ujCeY zVrG0%YH>k+UU8}>`(#cg9e&2lTdc_$rFq%KAPowW9hgEGnk#~>ut;dqBf zaDrm5#|LI0?*rTB-Ao=#j6#!HSS=W3Cfl;giiiQV6?200!a$Mu1x1ZxBUcUere delta 296 zcmZqYKf}j+nwOW00SLkr-=?ul#mteGJ2a`HJwFH!Eq%=n_z;)49V;?!HL1x1;8C7NuLb(wUy zS(7tL^RkQCfaXljU diff --git a/py/ai.py b/py/ai.py index ae5d692..c51f2d2 100644 --- a/py/ai.py +++ b/py/ai.py @@ -9,9 +9,12 @@ class AI: model=model, messages=messages, stream=True, - options={"temperature": 0.8}, + options={"temperature": 0.5}, ) + for i in messages: + print(i) + return_class.ai_response[access_token] = "" for chunk in stream: From d6e6cca0db247a84f82fef0972ea0186528bc87c Mon Sep 17 00:00:00 2001 From: YasinOnm08 Date: Fri, 20 Sep 2024 09:22:14 +0200 Subject: [PATCH 06/10] console.log weg --- app/ProcessAPI.js | 1 - 1 file changed, 1 deletion(-) diff --git a/app/ProcessAPI.js b/app/ProcessAPI.js index 0aaced7..bfd94dd 100644 --- a/app/ProcessAPI.js +++ b/app/ProcessAPI.js @@ -10,7 +10,6 @@ onmessage = function (e) { messages: messages, access_token: access_token }; - console.log(messages) switch (functionName) { case "getAccess": console.log("getting access...") From f9d3a1f235ed1071d979fce396350d8d9b24244f Mon Sep 17 00:00:00 2001 From: YasinOnm08 Date: Fri, 20 Sep 2024 09:58:13 +0200 Subject: [PATCH 07/10] ai works again? --- app/InputOutputHandler.tsx | 28 +++++++++------------------- app/ProcessAPI.js | 21 +++++++++++---------- 2 files changed, 20 insertions(+), 29 deletions(-) diff --git a/app/InputOutputHandler.tsx b/app/InputOutputHandler.tsx index 6f428dc..288aaa4 100644 --- a/app/InputOutputHandler.tsx +++ b/app/InputOutputHandler.tsx @@ -31,15 +31,14 @@ const InputOutputBackend: React.FC = () => { role: string content: string } - type SystemPrompt = { - - } const handleSendClick = (message:string) => { - var system:Message = {role:"system" ,content:"You are a helpful assistant that gives short answers."} + var system:Message = {role:"system" ,content:"You are a helpful assistant."} - addMessage("user",message); - HandlePostRequest(messages, "phi3.5", system) + addMessage("user", message); + console.log("added User Message") + + HandlePostRequest([...messages, { role: "user", content: message }], "phi3.5", system); }; const [messages, setMessages] = useState([ @@ -65,21 +64,12 @@ const InputOutputBackend: React.FC = () => { } } },[]) - - const HandleGetRequest = (messages: Message[], ai_model: string, system_prompt: Message) => { - if (workerRef.current) { - workerRef.current.postMessage({ functionName: "getResponse", access_token: accessToken, messages: messages, ai_model: ai_model, system_prompt: system_prompt }) - workerRef.current.onmessage = (e) => { - addMessage("assistant",e.data) - } - } - } - - const HandlePostRequest = (messages: Message[], ai_model: string, system_prompt: Message) => { - if (workerRef.current) { + + const HandlePostRequest = (messages: Message[], ai_model: string, system_prompt: Message) => { + if (workerRef.current) { workerRef.current.postMessage({ functionName: "postRequest", access_token: accessToken, messages: messages, ai_model: ai_model, system_prompt: system_prompt }) workerRef.current.onmessage = (e) => { - HandleGetRequest(messages,ai_model,system_prompt) + addMessage("assistant",e.data) } } } diff --git a/app/ProcessAPI.js b/app/ProcessAPI.js index bfd94dd..a1f3a6d 100644 --- a/app/ProcessAPI.js +++ b/app/ProcessAPI.js @@ -4,12 +4,21 @@ import { type } from 'os'; onmessage = function (e) { const { functionName = "getAccess", access_token = "", messages = [], ai_model = "phi3.5", system_prompt = {role:"system" ,content: "You are a helpful assistant that gives short answers"}} = e.data - let data = { ai_model: ai_model, messages: messages, access_token: access_token }; + + const getResponse = () => { + axios.get('https://localhost:5000/interstellar/api/ai_get?access_token=' + access_token) + .then(Response => { + postMessage(Response.data.response) + }).catch(error => { + console.error("Error with GET response request:", error) + }) + } + switch (functionName) { case "getAccess": console.log("getting access...") @@ -26,19 +35,11 @@ onmessage = function (e) { console.log(messages) axios.post('https://localhost:5000/interstellar/api/ai_send', data) .then(Response => { - postMessage(Response.data) + getResponse() }).catch(error => { console.error("Error:", error) }) break - case "getResponse": - axios.get('https://localhost:5000/interstellar/api/ai_get?access_token=' + access_token) - .then(Response => { - postMessage(Response.data.response) - }).catch(error => { - console.error("Error with GET response request:", error) - }) - break } From f7cab6aec0333c097820ab2b8ab349b12a963bea Mon Sep 17 00:00:00 2001 From: YasinOnm08 Date: Fri, 20 Sep 2024 10:54:21 +0200 Subject: [PATCH 08/10] repush --- app/ProcessAPI.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/ProcessAPI.js b/app/ProcessAPI.js index a1f3a6d..d02861b 100644 --- a/app/ProcessAPI.js +++ b/app/ProcessAPI.js @@ -11,9 +11,14 @@ onmessage = function (e) { }; const getResponse = () => { + messageComplete:boolean = false + while(!messageComplete) axios.get('https://localhost:5000/interstellar/api/ai_get?access_token=' + access_token) .then(Response => { postMessage(Response.data.response) + if (Response.data.status == 200) { + messageComplete = true + } }).catch(error => { console.error("Error with GET response request:", error) }) From 1ee7d55e490153b232c515243ca64b7b29a7401b Mon Sep 17 00:00:00 2001 From: Patrick_Pluto Date: Fri, 20 Sep 2024 11:15:40 +0200 Subject: [PATCH 09/10] ahhh --- py/db.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 py/db.py diff --git a/py/db.py b/py/db.py new file mode 100644 index 0000000..e69de29 From 4a183c0c89611888cdec2b52fd0a43dd59f9b195 Mon Sep 17 00:00:00 2001 From: Patrick_Pluto Date: Fri, 20 Sep 2024 11:15:42 +0200 Subject: [PATCH 10/10] wha --- py/api.py | 9 +++++++++ py/db.py | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/py/api.py b/py/api.py index b25e4d4..a5d2a97 100644 --- a/py/api.py +++ b/py/api.py @@ -2,6 +2,7 @@ from flask import Flask, request, jsonify from flask_cors import CORS import secrets from ai import AI +from db import DB class API: @@ -9,6 +10,7 @@ class API: self.app = Flask(__name__) self.ai_response = {} self.ai = AI() + self.db = DB() CORS(self.app) def run(self): @@ -36,6 +38,13 @@ class API: return jsonify({'status': 401, 'error': 'Invalid access token'}) return jsonify({'status': 200, 'response': self.ai_response[data]}) + @self.app.route('/interstellar/api/db', methods=['POST']) + def db_manipulate(): + action = request.args.get('action') + if action == "create_account": + print("ahh") + + ssl_context = ('cert.pem', 'key.pem') self.app.run(debug=True, host='0.0.0.0', port=5000, ssl_context=ssl_context) diff --git a/py/db.py b/py/db.py index e69de29..5116a93 100644 --- a/py/db.py +++ b/py/db.py @@ -0,0 +1,41 @@ +import json +import hashlib + + +class DB: + def __init__(self): + self.database = {} + + def _hash_password(self, password: str) -> str: + salt = "your_secret_salt" + hashed_password = hashlib.sha256((password + salt).encode()).hexdigest() + return hashed_password + + def add_user(self, username: str, password: str) -> None: + hashed_password = self._hash_password(password) + user_data = {"hashed_password": hashed_password} + self.database[username] = user_data + + def update_password(self, username: str, old_password: str, new_password: str) -> bool: + if not self.check_credentials(username, old_password): + return False + + hashed_new_password = self._hash_password(new_password) + self.database[username].update({"hashed_password": hashed_new_password}) + return True + + def check_credentials(self, username: str, password: str) -> bool: + if username not in self.database: + return False + + stored_hashed_password = self.database[username]["hashed_password"] + entered_hashed_password = self._hash_password(password) + return stored_hashed_password == entered_hashed_password + + def get_additional_info(self, username: str, password: str) -> dict | None: + if not self.check_credentials(username, password): + return None + + send_back = self.database[username] + del send_back['hashed_password'] + return send_back \ No newline at end of file