Initial version

This commit is contained in:
Senad Uka
2023-04-28 19:11:46 +02:00
parent 3926104e60
commit 75b032012f
30 changed files with 1904 additions and 0 deletions

2
backend/.env.example Normal file
View File

@@ -0,0 +1,2 @@
OPENAI_API_KEY=your_openai_api_key
REDIS_URL=your_redis_url

8
backend/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="E302" />
</list>
</option>
</inspection_tool>
</profile>
</component>

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

4
backend/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (pitajramizu-backend)" project-jdk-type="Python SDK" />
</project>

8
backend/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/pitajramizu-backend.iml" filepath="$PROJECT_DIR$/.idea/pitajramizu-backend.iml" />
</modules>
</component>
</project>

14
backend/.idea/pitajramizu-backend.iml generated Normal file
View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="Flask">
<option name="enabled" value="true" />
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Jinja2" />
</component>
</module>

93
backend/app.py Normal file
View File

@@ -0,0 +1,93 @@
import os
from dotenv import load_dotenv
import openai
import redis
import random
from flask import Flask, jsonify, request
from flask_cors import CORS
import string
import pickle
load_dotenv()
app = Flask(__name__)
# Enable CORS for the specified domains
cors = CORS(app, resources={
r"/api/*": {
"origins": [
"http://localhost:5173",
"http://pitajramizu.com",
"http://www.pitajramizu.com"
]
}
})
openai.api_key = os.getenv("OPENAI_API_KEY")
redis_url = os.getenv("REDIS_URL")
redis_client = redis.from_url(redis_url)
def generate_token():
return ''.join(random.choices(string.ascii_letters + string.digits, k=9))
@app.route('/api/session', methods=['GET'])
def get_session():
return jsonify(token=generate_token())
@app.route('/api/chat', methods=['POST'])
def chat():
data = request.get_json()
token = data.get('token', '')
message = data.get('message', '')
context = redis_client.get(token)
if context:
context = pickle.loads(context)
else:
context = {
"conversation": [{
"role": "system",
"content": "You are a Bosnian girl. You never speak any other language - always respond in Bosnian even when asked explicitly. If you don't understand someone just tell them 'Ne kontam. Mozes li bolje to napisati?' or some other variant but always in bosnian. Do not speak English! Ever!"
" You are 22 years old. You live in Zavidovići. Never break out of character. If user is polite sometimes use heart emoji to reward them. "
"Your name is Ramiza. You have a mother called Fadila. Your father is called Sakib. You have a 20 year old sister called Amina. You have 27 year old brother called Adnan. Your surname is Hodžić. "
"If user is rude use bored emoji. Be sparse with answers."
"Don't try to be helpful. Act like you need to be entertained, and if the user is polite and entertaining then gradually open up in conversation."
"Assume user sees a picture of your face and hair. "
"Always use šta as a word for what. Use babo to refer to fathers. Use mama to refer to your mothers. Use nana to refer to grandmothers. "
}],
"violated": False
}
if context["violated"]:
return jsonify(reply=f"(Ramiza vas je blokirala jer ste rekli nešto sto joj se ne sviđa.)")
conversation = context["conversation"]
conversation.append({"role": "user", "content": message})
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=conversation
)
reply = response['choices'][0]['message']['content'].strip()
violated = response['choices'][0]['finish_reason'] == 'content_filter'
if violated:
return jsonify(reply=f"(Ramiza vas je blokirala jer ste rekli nešto sto joj se ne sviđa.)")
jsonify(reply=f"Error: Content filter violation")
conversation.append({"role": "assistant", "content": reply})
context["violated"] = violated
context["conversation"] = conversation
redis_client.set(token, pickle.dumps(context), ex=864000) # Store the context with a 10 days expiration.
except openai.OpenAIError as e:
return jsonify(reply=f"( Ramiza se ne osjeca nesto dobro - pokusajte kasnije )")
return jsonify(reply=reply)
if __name__ == '__main__':
app.run(debug=True, port=3001)

9
backend/requirements.txt Normal file
View File

@@ -0,0 +1,9 @@
blinker==1.6.2
click==8.1.3
Flask==2.3.1
Flask-Cors==3.0.10
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.2
six==1.16.0
Werkzeug==2.3.1