Skip to content

Commit b885a44

Browse files
committed
DB and template added
1 parent f652359 commit b885a44

15 files changed

+483
-30
lines changed

date_parser.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# date_parser.py
2+
from datetime import datetime
3+
4+
def parse_date(date_str, output_format='%d/%m/%Y'):
5+
date_formats = ['%d/%m/%Y', '%Y-%m-%d', '%d-%m-%Y', '%m/%d/%Y']
6+
for fmt in date_formats:
7+
try:
8+
parsed_date = datetime.strptime(date_str, fmt)
9+
return parsed_date.strftime(output_format)
10+
except ValueError:
11+
continue
12+
return None
13+
14+
def extract_day_month(date_str):
15+
date_formats = ['%d/%m/%Y', '%Y-%m-%d', '%d-%m-%Y', '%m/%d/%Y']
16+
for fmt in date_formats:
17+
try:
18+
parsed_date = datetime.strptime(date_str, fmt)
19+
return parsed_date.strftime('%d/%m') # Chỉ trả về ngày và tháng
20+
except ValueError:
21+
continue
22+
return None

main.py

+149
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import getpass
2+
import os
3+
4+
from typing import *
5+
import json
6+
import sys
7+
import time
8+
import subprocess
9+
import traceback
10+
from tempfile import NamedTemporaryFile
11+
# from google.colab.patches import cv2_imshow
12+
13+
import requests
14+
import openai
15+
# from dotenv import load_dotenv
16+
import xml.etree.ElementTree as ET
17+
from datetime import datetime
18+
import re
19+
from date_parser import extract_day_month
20+
21+
22+
# if not os.environ.get('OPENAI_API_KEY'):
23+
# os.environ['OPENAI_API_KEY'] = getpass.getpass("Enter the OpenAI API Key(which starts with sk-): ")
24+
25+
# load_dotenv() # This loads the variables from .env
26+
27+
api_key = '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'
28+
assistant_id = 'asst_FECUwGnkMA50kVsyeGcbdxJI'
29+
30+
client = openai.Client(api_key=api_key)
31+
32+
def execute_python_code(s: str) -> str:
33+
with NamedTemporaryFile(suffix='.py', delete=False) as temp_file:
34+
temp_file_name = temp_file.name
35+
temp_file.write(s.encode('utf-8'))
36+
temp_file.flush()
37+
try:
38+
result = subprocess.run(
39+
['python', temp_file_name],
40+
capture_output=True,
41+
text=True,
42+
check=True
43+
)
44+
return result.stdout
45+
except subprocess.CalledProcessError as e:
46+
return e.stderr
47+
finally:
48+
import os
49+
os.remove(temp_file_name)
50+
51+
def get_lottery_result(lottery_name, date):
52+
# https://xskt.com.vn/rss-feed/mien-bac-xsmb.rss
53+
# return "Toi khong biet!"
54+
# Chuyển đổi ngày từ chuỗi sang đối tượng datetime
55+
converted_date = extract_day_month(date)
56+
if converted_date:
57+
print(f"Converted date: {converted_date}")
58+
else:
59+
print("Invalid date format")
60+
61+
date = datetime.strptime(converted_date, '%d/%m')
62+
rss_url = 'https://xskt.com.vn/rss-feed/mien-bac-xsmb.rss'
63+
64+
# Tải dữ liệu RSS từ URL
65+
response = requests.get(rss_url)
66+
root = ET.fromstring(response.content)
67+
68+
# Tìm kiếm kết quả trong các mục
69+
for item in root.findall('.//item'):
70+
title = item.find('title').text
71+
# Kiểm tra xem tiêu đề có chứa chuỗi ngày/tháng hay không
72+
if converted_date in title:
73+
return item.find('description').text
74+
75+
return "Không tìm thấy kết quả xổ số cho ngày này."
76+
77+
def run_assistant(client, assistant_id, thread_id):
78+
# Create a new run for the given thread and assistant
79+
run = client.beta.threads.runs.create(
80+
thread_id=thread_id,
81+
assistant_id=assistant_id
82+
)
83+
84+
# Loop until the run status is either "completed" or "requires_action"
85+
while run.status == "in_progress" or run.status == "queued":
86+
time.sleep(3)
87+
run = client.beta.threads.runs.retrieve(
88+
thread_id=thread_id,
89+
run_id=run.id
90+
)
91+
92+
# At this point, the status is either "completed" or "requires_action"
93+
if run.status == "completed":
94+
return client.beta.threads.messages.list(
95+
thread_id=thread_id
96+
)
97+
if run.status == "requires_action":
98+
tool_call = run.required_action.submit_tool_outputs.tool_calls[0]
99+
tool_outputs = []
100+
if tool_call.function.name == "execute_python_code":
101+
generated_python_code = json.loads(tool_call.function.arguments)['code']
102+
result = execute_python_code(generated_python_code)
103+
tool_outputs.append(
104+
{
105+
"tool_call_id": tool_call.id,
106+
"output": result,
107+
},
108+
)
109+
# Mike add
110+
elif tool_call.function.name == "get_lottery_result":
111+
lottery_name = json.loads(tool_call.function.arguments)['lottery_name']
112+
draw_date = json.loads(tool_call.function.arguments)['draw_date']
113+
result = get_lottery_result(lottery_name, draw_date)
114+
tool_outputs.append(
115+
{
116+
"tool_call_id": tool_call.id,
117+
"output": result,
118+
},
119+
)
120+
121+
if tool_outputs:
122+
run = client.beta.threads.runs.submit_tool_outputs(
123+
thread_id=thread_id,
124+
run_id=run.id,
125+
tool_outputs=tool_outputs
126+
)
127+
128+
if __name__ == "__main__":
129+
script = input("python code to execute: \n")
130+
131+
132+
# Create a new thread
133+
thread = client.beta.threads.create()
134+
thread_id = thread.id
135+
# Create a new thread message with the provided task
136+
thread_message = client.beta.threads.messages.create(
137+
thread.id,
138+
role="user",
139+
content=script,
140+
)
141+
142+
# assistant_id, thread_id = setup_assistant(client, script)
143+
print(f"Debugging: Useful for checking the generated agent in the playground. https://platform.openai.com/playground?mode=assistant&assistant={assistant_id}")
144+
print(f"Debugging: Useful for checking logs. https://platform.openai.com/playground?thread={thread_id}")
145+
146+
messages = run_assistant(client, assistant_id, thread_id)
147+
148+
# message_dict = json.loads(messages)
149+
print(messages)

oapi/customBot/__init__.py

Whitespace-only changes.

oapi/customBot/admin.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from django.contrib import admin
2+
3+
# Register your models here.

oapi/customBot/apps.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from django.apps import AppConfig
2+
3+
4+
class CustombotConfig(AppConfig):
5+
default_auto_field = "django.db.models.BigAutoField"
6+
name = "customBot"
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Generated by Django 4.2.9 on 2024-01-24 04:24
2+
3+
from django.db import migrations, models
4+
5+
6+
class Migration(migrations.Migration):
7+
8+
initial = True
9+
10+
dependencies = []
11+
12+
operations = [
13+
migrations.CreateModel(
14+
name="UserProfile",
15+
fields=[
16+
(
17+
"id",
18+
models.BigAutoField(
19+
auto_created=True,
20+
primary_key=True,
21+
serialize=False,
22+
verbose_name="ID",
23+
),
24+
),
25+
("username", models.CharField(max_length=150)),
26+
("assitantId", models.CharField(max_length=200)),
27+
("threadID", models.CharField(max_length=200)),
28+
],
29+
),
30+
]

oapi/customBot/migrations/__init__.py

Whitespace-only changes.

oapi/customBot/models.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from django.db import models
2+
3+
# Create your models here.
4+
5+
6+
class UserProfile(models.Model):
7+
username = models.CharField(max_length=150)
8+
assitantId = models.CharField(max_length=200)
9+
threadID = models.CharField(max_length=200)
10+
11+
# email = models.EmailField()
12+
# password = models.CharField(max_length=100)
13+
# user_type = models.CharField(max_length=20, choices=[('admin', 'Admin'),('employee', 'Employee'),('student', 'Student'), ('hostelOwner', 'Hostel Owner')])
14+

oapi/customBot/templates/index.html

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<link rel="stylesheet" href="styles.css">
7+
<style>
8+
body {
9+
margin: 0;
10+
font-family: Arial, sans-serif;
11+
}
12+
13+
.chat-container {
14+
max-width: 600px;
15+
margin: 0 auto;
16+
padding: 20px;
17+
}
18+
19+
.chat {
20+
border: 1px solid #ccc;
21+
padding: 10px;
22+
border-radius: 10px;
23+
overflow-y: scroll;
24+
max-height: 400px;
25+
}
26+
27+
.message {
28+
margin: 10px;
29+
padding: 10px;
30+
border-radius: 10px;
31+
max-width: 70%;
32+
}
33+
34+
.received {
35+
background-color: #f2f2f2;
36+
align-self: flex-start;
37+
}
38+
39+
.sent {
40+
background-color: #dcf8c6;
41+
align-self: flex-end;
42+
}
43+
44+
.message-input {
45+
display: flex;
46+
margin-top: 20px;
47+
}
48+
49+
.message-input input {
50+
flex: 1;
51+
padding: 10px;
52+
border: none;
53+
border-radius: 5px;
54+
}
55+
56+
.message-input button {
57+
padding: 10px 20px;
58+
border: none;
59+
background-color: #007bff;
60+
color: #fff;
61+
border-radius: 5px;
62+
cursor: pointer;
63+
}
64+
</style>
65+
<title>Chat with Assistant</title>
66+
</head>
67+
<body>
68+
<div class="chat-container">
69+
<div class="chat" id="chat-container">
70+
<!-- Existing messages go here -->
71+
</div>
72+
<div class="message-input">
73+
<input type="text" id="user-input" placeholder="Type your message...">
74+
<button id="send-button">Send</button>
75+
</div>
76+
</div>
77+
78+
<script>
79+
document.addEventListener('DOMContentLoaded', function () {
80+
const chatContainer = document.getElementById('chat-container');
81+
const userInput = document.getElementById('user-input');
82+
const sendButton = document.getElementById('send-button');
83+
84+
sendButton.addEventListener('click', async function () {
85+
const userMessage = userInput.value;
86+
console.log("user message", userMessage);
87+
try {
88+
const response = await fetch('http://localhost:3000/answer', {
89+
method: 'POST',
90+
headers: {
91+
'Content-Type': 'application/json',
92+
},
93+
body: JSON.stringify({
94+
question: userMessage,
95+
assitant_id: 'asst_8klujY8GWez2QcUITxD6AFlQ', // Replace with your actual assistant ID
96+
}),
97+
});
98+
99+
const data = await response.json();
100+
101+
// Add the assistant's response to the chat
102+
const assistantResponseDiv = document.createElement('div');
103+
assistantResponseDiv.className = 'message received';
104+
assistantResponseDiv.innerHTML = `<div class="message-content">${data.answer}</div>`;
105+
chatContainer.appendChild(assistantResponseDiv);
106+
107+
// Clear the user input
108+
userInput.value = '';
109+
} catch (error) {
110+
console.error('Error asking question:', error);
111+
}
112+
});
113+
});
114+
</script>
115+
</body>
116+
</html>
117+
118+
119+

oapi/customBot/tests.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from django.test import TestCase
2+
3+
# Create your tests here.

oapi/customBot/urls.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
2+
from django.urls import path
3+
from .views import *
4+
5+
urlpatterns = [
6+
path('', home, name='home'),
7+
]

oapi/customBot/views.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from django.shortcuts import render
2+
3+
# Create your views here.
4+
5+
def home(request):
6+
return render(request,'index.html')

0 commit comments

Comments
 (0)