Skip to content
Snippets Groups Projects
Commit a433ebd4 authored by nniehaus's avatar nniehaus
Browse files

finished

parent 5238c9b3
No related branches found
No related tags found
No related merge requests found
......@@ -33,7 +33,7 @@ To use the applictaion from your local directory, **run 'flask --app client run'
## Features
Th eliza catbot gives appropriate answers to whatever message you sent it.
The eliza catbot gives appropriate answers to whatever message you sent it.
The guessing game works in the way that the computer choses a random integer number and you have to guess it (message in your guesses).
......
No preview for this file type
File added
......@@ -5,8 +5,8 @@ import datetime
app = Flask(__name__)
HUB_AUTHKEY = '1234567890'
HUB_URL = 'http://localhost:5555'
HUB_AUTHKEY = 'Crr-K3d-2N'
HUB_URL = 'https://temporary-server.de'
CHANNELS = None
LAST_CHANNEL_UPDATE = None
......
......@@ -22,11 +22,11 @@ app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass') # configuration
app.app_context().push() # create an app context before initializing db
HUB_URL = 'http://localhost:5555'
HUB_AUTHKEY = '1234567890'
HUB_URL = 'https://temporary-server.de'
HUB_AUTHKEY = 'Crr-K3d-2N'
CHANNEL_AUTHKEY = '22334455'
CHANNEL_NAME = "The Eliza Chatbot"
CHANNEL_ENDPOINT = "http://localhost:5002"
CHANNEL_ENDPOINT = "http://vm713.rz.uni-osnabrueck.de/user119/elizachannel.wsgi"
CHANNEL_FILE = 'eliza_messages.json'
@app.cli.command('register')
......@@ -89,6 +89,7 @@ def send_message():
# add message to messages
messages = read_messages()
messages.append({'content':message['content'], 'sender':message['sender'], 'timestamp':message['timestamp']})
#Eliza bot choses response based on the input message
response = eliza.respond(message['content'])
messages.append({'content': response, 'sender':"Eliza", 'timestamp':datetime.datetime.now().isoformat()})
save_messages(messages)
......
from elizachannel import app
application = app
\ No newline at end of file
## channel.py - a simple message channel
##
from flask import Flask, request, render_template, jsonify
import json
import requests
# Class-based application configuration
class ConfigClass(object):
""" Flask application config """
# Flask settings
SECRET_KEY = 'This is an INSECURE secret!! DO NOT use this in production!!'
# Create Flask app
app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass') # configuration
app.app_context().push() # create an app context before initializing db
HUB_URL = 'http://localhost:5555'
HUB_AUTHKEY = '1234567890'
CHANNEL_AUTHKEY = '0987654321'
CHANNEL_NAME = "The One and Only Channel"
CHANNEL_ENDPOINT = "http://localhost:5001" # don't forget to adjust in the bottom of the file
CHANNEL_FILE = 'messages.json'
@app.cli.command('register')
def register_command():
global CHANNEL_AUTHKEY, CHANNEL_NAME, CHANNEL_ENDPOINT
# send a POST request to server /channels
response = requests.post(HUB_URL + '/channels', headers={'Authorization': 'authkey ' + HUB_AUTHKEY},
data=json.dumps({
"name": CHANNEL_NAME,
"endpoint": CHANNEL_ENDPOINT,
"authkey": CHANNEL_AUTHKEY}))
if response.status_code != 200:
print("Error creating channel: "+str(response.status_code))
return
def check_authorization(request):
global CHANNEL_AUTHKEY
# check if Authorization header is present
if 'Authorization' not in request.headers:
return False
# check if authorization header is valid
if request.headers['Authorization'] != 'authkey ' + CHANNEL_AUTHKEY:
return False
return True
@app.route('/health', methods=['GET'])
def health_check():
global CHANNEL_NAME
if not check_authorization(request):
return "Invalid authorization", 400
return jsonify({'name':CHANNEL_NAME}), 200
# GET: Return list of messages
@app.route('/', methods=['GET'])
def home_page():
if not check_authorization(request):
return "Invalid authorization", 400
# fetch channels from server
return jsonify(read_messages())
# POST: Send a message
@app.route('/', methods=['POST'])
def send_message():
# fetch channels from server
# check authorization header
if not check_authorization(request):
return "Invalid authorization", 400
# check if message is present
message = request.json
if not message:
return "No message", 400
if not 'content' in message:
return "No content", 400
if not 'sender' in message:
return "No sender", 400
if not 'timestamp' in message:
return "No timestamp", 400
# add message to messages
messages = read_messages()
messages.append({'content':message['content'], 'sender':message['sender'], 'timestamp':message['timestamp']})
save_messages(messages)
return "OK", 200
def read_messages():
global CHANNEL_FILE
try:
f = open(CHANNEL_FILE, 'r')
except FileNotFoundError:
return []
try:
messages = json.load(f)
except json.decoder.JSONDecodeError:
messages = []
f.close()
return messages
def save_messages(messages):
global CHANNEL_FILE
with open(CHANNEL_FILE, 'w') as f:
json.dump(messages, f)
# Start development web server
if __name__ == '__main__':
app.run(port=5001, debug=True)
## ggchannel.py - a simple guessing game channel
## guessinggamechannel.py - a simple guessing game channel to guess a random number
##
from flask import Flask, request, render_template, jsonify
......@@ -6,7 +6,6 @@ import json
import requests
import datetime
import re
import numpy as np
import random
# Class-based application configuration
......@@ -21,15 +20,13 @@ app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass') # configuration
app.app_context().push() # create an app context before initializing db
HUB_URL = 'http://localhost:5555'
HUB_AUTHKEY = '1234567890'
HUB_URL = 'https://temporary-server.de'
HUB_AUTHKEY = 'Crr-K3d-2N'
CHANNEL_AUTHKEY = '0987654321'
CHANNEL_NAME = "The Guessing Game - Can you gess the right number?"
CHANNEL_ENDPOINT = "http://localhost:5001" # don't forget to adjust in the bottom of the file
CHANNEL_NAME = "Can you gess the right number?"
CHANNEL_ENDPOINT = "http://vm713.rz.uni-osnabrueck.de/user119/guessinggamechannel.wsgi" # don't forget to adjust in the bottom of the file
CHANNEL_FILE = 'gg_messages.json'
intToGuess = random.randint(100000000,100000000)
@app.cli.command('register')
def register_command():
global CHANNEL_AUTHKEY, CHANNEL_NAME, CHANNEL_ENDPOINT
......@@ -90,7 +87,8 @@ def send_message():
# add message to messages
messages = read_messages()
messages.append({'content':message['content'], 'sender':message['sender'], 'timestamp':message['timestamp']})
# Random integer as guessing number
intToGuess = random.randint(100000000,100000000)
# check for digit in message
digits = re.findall("[0-9]", message['content'])
if digits:
......
from guessinggamechannel import app
application = app
\ No newline at end of file
## channel.py - a simple message channel
from flask import Flask, request, render_template, jsonify
import json
import requests
# Class-based application configuration
class ConfigClass(object):
""" Flask application config """
# Flask settings
SECRET_KEY = 'This is an INSECURE secret!! DO NOT use this in production!!'
# Create Flask app
app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass') # configuration
app.app_context().push() # create an app context before initializing db
HUB_URL = 'http://localhost:5555'
HUB_AUTHKEY = '1234567890'
CHANNEL_AUTHKEY = '22334455'
CHANNEL_NAME = "The Lousy Channel"
CHANNEL_ENDPOINT = "http://localhost:5002"
CHANNEL_FILE = 'messages.json'
@app.cli.command('register')
def register_command():
global CHANNEL_AUTHKEY, CHANNEL_NAME, CHANNEL_ENDPOINT
# send a POST request to server /channels
response = requests.post(HUB_URL + '/channels', headers={'Authorization': 'authkey ' + HUB_AUTHKEY},
data=json.dumps({
"name": CHANNEL_NAME,
"endpoint": CHANNEL_ENDPOINT,
"authkey": CHANNEL_AUTHKEY}))
if response.status_code != 200:
print("Error creating channel: "+str(response.status_code))
return
def check_authorization(request):
global CHANNEL_AUTHKEY
# check if Authorization header is present
if 'Authorization' not in request.headers:
return False
# check if authorization header is valid
if request.headers['Authorization'] != 'authkey ' + CHANNEL_AUTHKEY:
return False
return True
@app.route('/health', methods=['GET'])
def health_check():
global CHANNEL_NAME
if not check_authorization(request):
return "Invalid authorization", 400
return jsonify({'name':CHANNEL_NAME}), 200
# GET: Return list of messages
@app.route('/', methods=['GET'])
def home_page():
if not check_authorization(request):
return "Invalid authorization", 400
# fetch channels from server
return jsonify(read_messages())
# POST: Send a message
@app.route('/', methods=['POST'])
def send_message():
# fetch channels from server
# check authorization header
if not check_authorization(request):
return "Invalid authorization", 400
# check if message is present
message = request.json
if not message:
return "No message", 400
if not 'content' in message:
return "No content", 400
if not 'sender' in message:
return "No sender", 400
if not 'timestamp' in message:
return "No timestamp", 400
# add message to messages
messages = read_messages()
messages.append({'content':message['content'], 'sender':message['sender'], 'timestamp':message['timestamp']})
save_messages(messages)
return "OK", 200
def read_messages():
global CHANNEL_FILE
try:
f = open(CHANNEL_FILE, 'r')
except FileNotFoundError:
return []
try:
messages = json.load(f)
except json.decoder.JSONDecodeError:
messages = []
f.close()
return messages
def save_messages(messages):
global CHANNEL_FILE
with open(CHANNEL_FILE, 'w') as f:
json.dump(messages, f)
# Start development web server
if __name__ == '__main__':
app.run(port=5002, debug=True)
from transformers import GPT2LMHeadModel, GPT2Tokenizer
model_name = "gpt2"
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model = GPT2LMHeadModel.from_pretrained(model_name)
# Assuming dataset is a list of (input_text, output_text) pairs
from transformers import GPT2LMHeadModel, GPT2Tokenizer, TextDataset, DataCollatorForLanguageModeling, Trainer, TrainingArguments
# Tokenize input and output texts
input_texts = [tokenizer.encode(pair[0], add_special_tokens=False) for pair in dataset]
output_texts = [tokenizer.encode(pair[1], add_special_tokens=False) for pair in dataset]
# Create a TextDataset and DataCollator
text_dataset = TextDataset(tokenizer, input_texts, output_texts)
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm_probability=0.15)
# Set up training arguments and trainer
training_args = TrainingArguments(
output_dir="./results",
overwrite_output_dir=True,
num_train_epochs=3,
per_device_train_batch_size=16,
save_steps=10_000,
save_total_limit=2,
)
trainer = Trainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=text_dataset,
)
# Train the model
trainer.train()
model.save_pretrained("./gpt2_chatbot")
tokenizer.save_pretrained("./gpt2_chatbot")
# To load the fine-tuned model and tokenizer
model = GPT2LMHeadModel.from_pretrained("./gpt2_chatbot")
tokenizer = GPT2Tokenizer.from_pretrained("./gpt2_chatbot")
@app.route("/chat", methods=["POST"])
def chat():
input_text = request.json["input_text"]
tokens = tokenizer.encode(input_text, return_tensors="pt")
output = model.generate(tokens, max_length=50, num_return_sequences=1)
response_text = tokenizer.decode(output[0], skip_special_tokens=True)
return jsonify({"response_text": response_text})
from bs4 import BeautifulSoup
import requests
import nltk
nltk.download("punkt")
from nltk.tokenize import word_tokenize, sent_tokenize
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
text = soup.get_text()
word_tokens = word_tokenize(text)
sentence_tokens = sent_tokenize(text)
\ No newline at end of file
flask
flask-sqlalchemy
requests
transformers
\ No newline at end of file
requests
\ No newline at end of file
// Function to send a message to the server using AJAX
function sendMessage() {
var message = document.getElementById("message").value;
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure the request
xhr.open("POST", "/", true);
xhr.setRequestHeader("Content-Type", "application/json");
// Define what happens on successful data submission
xhr.onload = function() {
if (xhr.status == 200) {
// Refresh messages
getMessages();
}
};
// Send the request
xhr.send(JSON.stringify({"message": message}));
}
// Function to retrieve messages from the server using AJAX
function getMessages() {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure the request
xhr.open("GET", "/", true);
// Define what happens on successful data retrieval
xhr.onload = function() {
if (xhr.status == 200) {
// Parse the JSON response
var messages = JSON.parse(xhr.responseText);
// Clear existing messages
var messagesContainer = document.getElementById("messages");
messagesContainer.innerHTML = "";
// Add new messages to the messages container
messages.forEach(function(message) {
var div = document.createElement("div");
div.className = "message";
div.textContent = message;
messagesContainer.appendChild(div);
});
}
};
// Send the request
xhr.send();
}
\ No newline at end of file
......@@ -11,7 +11,7 @@
<ul>
{% for channel in channels %}
<li><a href="/show?channel={{ channel.endpoint | urlencode }}">{{ channel.name }}</a></li>
<li><a href="{{ url_for('show_channel') }}?channel={{ channel.endpoint | urlencode }}">{{ channel.name }}</a></li>
{% endfor %}
</ul>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment