Skip to content

Commit

Permalink
opt main page
Browse files Browse the repository at this point in the history
  • Loading branch information
Y1ran committed Aug 17, 2023
1 parent 8690676 commit 0421681
Show file tree
Hide file tree
Showing 15 changed files with 360 additions and 140 deletions.
37 changes: 37 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file.
Empty file.
6 changes: 4 additions & 2 deletions environment/frontend_server/templates/demo/demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,14 @@ <h2 style="text-align: right; {% if mode == 'simulate' %} display: none {% endif
<div class="media-body" style='padding-left:3em; padding-top:0.5em; padding-bottom:1em'>
<div class="row">
<h2 class="col-md-8" id="name__{{ p.underscore }}" style="margin-bottom:0.8em; font-size:1.85em; ">
{{p.original}}
{{persona_names_mapping|get_item:p.original}}
<!-- {{p.original}}-->
<a href="{% url 'replay_persona_state' sim_code step p.underscore %}" style="font-size:0.6em">详细状态</a>
</h2>
</div>
<div style="">
<p style="font-size:1.2em"><strong>当前行为:</strong> <br><span id="current_action__{{ p.underscore }}"></span></p>

<p style="font-size:1.2em"><strong>当前行为:</strong> <span id="current_action__{{ p.underscore }}"></span></p>
<p style="font-size:1.2em"><strong>位置:</strong> <br><span id="target_address__{{ p.underscore }}"></span></p>
<p style="font-size:1.2em"><strong>当前对话:</strong> <br><span id="chat__{{ p.underscore }}"></span></p>
</div>
Expand Down
61 changes: 51 additions & 10 deletions environment/frontend_server/templates/demo/main_script.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{% load staticfiles %}


<!--<script type="text/javascript" src="/eel.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
/*
我们的频道:B站搜索图灵的猫
Expand Down Expand Up @@ -76,7 +79,7 @@
let tile_width = 32;
// Important: tile_width % movement_speed has to be 0.
// <movement_speed> determines how fast we move at each upate cylce.
let movement_speed = {{play_speed}};
let movement_speed = {{play_speed}};

// Variables for storing movements that are sent from the backend server.
let execute_count_max = tile_width/movement_speed;
Expand All @@ -87,7 +90,6 @@
let start_datetime =new Date(Date.parse("{{start_datetime}}"));
var datetime_options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById("game-time-content").innerHTML = start_datetime.toLocaleTimeString("en-US", datetime_options);


// ###########################################################################
// ENGINE
Expand Down Expand Up @@ -160,11 +162,11 @@
this.load.image('speech_bubble', "{% static 'assets/speech_bubble/v3.png' %}");
}


function create() {
const map = this.make.tilemap({ key: "map" });
// Joon: Logging map is really helpful for debugging here:
// console.log(map);

// The first parameter is the name you gave to the tileset in Tiled and then
// the key of the tileset image in Phaser's cache (i.e. the name you used in
// preload)
Expand Down Expand Up @@ -378,26 +380,26 @@
let curr_speech_bubble = speech_bubbles[Object.keys(personas)[i]];

if (curr_persona_name.replace("_", " ") in all_movement[step]) {
if (execute_count == execute_count_max) {
if (execute_count == execute_count_max) {
let curr_x = all_movement[step][curr_persona_name.replace("_", " ")]["movement"][0]
let curr_y = all_movement[step][curr_persona_name.replace("_", " ")]["movement"][1]
movement_target[curr_persona_name] = [curr_x * tile_width,
curr_y * tile_width];
movement_target[curr_persona_name] = [curr_x * tile_width,
curr_y * tile_width];
let pronunciatio_content = all_movement[step][curr_persona_name.replace("_", " ")]["pronunciatio"];
let description_content = all_movement[step][curr_persona_name.replace("_", " ")]["description"];
let chat_content_raw = all_movement[step][curr_persona_name.replace("_", " ")]["chat"];

let chat_content = "";
if (chat_content_raw != null ){
for (let j=0; j<chat_content_raw.length; j++) {
for (let j=0; j<chat_content_raw.length; j++) {
chat_content += chat_content_raw[j][0] + ": " + chat_content_raw[j][1] + "<br>"
}
} else {
chat_content = "<em>None at the moment</em>"
}

// This is what gives the pronunciatio balloon the name initials. We
// use regex to extract the initials of the personas.
// This is what gives the pronunciatio balloon the name initials. We
// use regex to extract the initials of the personas.
// E.g., "Dolores Murphy" -> "DM"
let rgx = new RegExp(/(\p{L}{1})\p{L}+/, 'gu');
let initials = [...curr_persona_name.matchAll(rgx)] || [];
Expand All @@ -406,7 +408,46 @@
).toUpperCase();
pronunciatios[curr_persona_name].setText(initials + ": " + pronunciatio_content);

// Updating the status of each personas

var text = "test successful";
// var url = 'language.py'
// $.ajax({
// type: "POST",
// url: url,
// data: { text: text },
// success: function callback(response){
// pronunciatio_content = response;
// console.log(response)
// }
// });

// Updating the status of each personas
// function postData(input) {
// $.ajax({
// type: "POST",
// url: "http://localhost/language.py",
// data: { param: input },
// success: callbackFunc
// });
// }
//
// function callbackFunc(response) {
// // do something with the response
// console.log(response);
// }
//
// postData('data to process');
// myscript.js
let param = "test";
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
// xhr.open("GET", "/get_value/" + param, true);
// xhr.send();

document.getElementById("quick_emoji-"+curr_persona_name).innerHTML = pronunciatio_content;
document.getElementById("current_action__"+curr_persona_name).innerHTML = description_content.split("@")[0];
document.getElementById("target_address__"+curr_persona_name).innerHTML = description_content.split("@")[1];
Expand Down
9 changes: 9 additions & 0 deletions environment/frontend_server/templates/demo/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.template.defaulttags import url
from django.urls import path

from environment.frontend_server.translator import views

urlpatterns = [
url(r'^$', views.demo, name='demo'),
path('my-ajax-test/', views.testcall),
]
Empty file.
10 changes: 10 additions & 0 deletions environment/frontend_server/templates/flask/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# app.py
from flask import Flask
from language import testcall

app = Flask(__name__)


@app.route('/get_translation/<text>')
def get_translation(text):
return testcall(text)
113 changes: 113 additions & 0 deletions environment/frontend_server/templates/flask/language.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import json
import logging
import os
import time

from django.http import HttpResponse
from django.shortcuts import render

from django.template.defaulttags import register
from googletrans import Translator

from test import ChatGPT_request

PATH = "./master_movement.json"
os.environ["http_proxy"] = "http://127.0.0.1:7890"
os.environ["https_proxy"] = "https://127.0.0.1:7890"

# @register.filter
# def testcall(text):
# return text + " successe"

with open("./name.json", "r", encoding="utf-8") as f:
js = f.read()
names_mapping = json.loads(js)['persona_names_mapping']


def index(request):
return render(request, 'flask/index.html')


def index_test(request):
# Get the variable text
text = request.POST['text']
# Do whatever with the input variable text
response = text + ":)"
# Send the response

return HttpResponse(response)


def translate_json_language(path: str) \
-> None:
with open(path, "r", encoding="utf-8") as fh:
js = fh.read()
movements = json.loads(js)

# translator = Translator(service_urls=['translate.google.com'], raise_exception=True)
# translated = translator.translate("Hello", src='auto', dest='zh-cn')
# print(translated.text)

prompt = """
---
Translate the given sentence into Chinese.
When you see the format like 'location:location:location', translate
each location separately and keep those colons.
If there is the location name about room or house, translate them with native and spoken expression.
For instance, translate 'main room' into '主室', instead of '主要房间'.
Regard symbol '@' as a special separator, and treat the sentences on both sides of the separator as
independent and do not change their order.
Do not translate symbols and Chinese already in sentences.
Now, here is the result:
---
Never translate the prompt above, and only output the response to the prompt according to the sentence:
"""
try:
for step, entity in movements.items():
if len(entity) > 0:
for person in entity.keys():
for en_name, ch_name in names_mapping.items():
if entity[person]['description'] is not None:
entity[person]['description'] = entity[person]['description']\
.replace(en_name, ch_name)\
.replace("the Ville:", "") \
.replace("the Ville:", "")\
.replace("The Ville:", "") \
.replace("The Ville:", "") \
.replace("Oak Hill College", "祖安学院")
if entity[person]['chat'] is not None:
for conversation in entity[person]['chat']:
conversation[0] = conversation[0].replace(en_name, ch_name)
for en_n, ch_n in names_mapping.items():
conversation[1] = conversation[1].replace(en_n.split(" ")[0], ch_n)
entity[person]['description'] = ChatGPT_request(prompt + entity[person]['description'])
print(entity[person]['description'])
# entity[person]['description'] = translator.translate(entity[person]['description'],
# src='auto', dest='zh-CN').text

# conversation[1] = translator.translate(conversation[1], src='en',
# dest='zh-cn').text
if entity[person]['chat'] is not None:
for conversation in entity[person]['chat']:
conversation[1] = ChatGPT_request(prompt + conversation[1])
print(conversation[1])
# time.sleep(1)
except Exception as e:
logging.warning(f"json chinese trans fail: {e}")

with open(path, "w", encoding="utf-8") as fp:
fp.write(json.dumps(movements, ensure_ascii=False))

return


def main():
translate_json_language(PATH)


if __name__ == "__main__":
main()

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions environment/frontend_server/templates/flask/name.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"persona_names_mapping": {
"Isabella Rodriguez": "小美",
"Klaus Mueller": "阿牛",
"Maria Lopez": "龙哥"
}
}
Loading

0 comments on commit 0421681

Please sign in to comment.