Skip to content

Commit

Permalink
move cartomancy drawing to backend
Browse files Browse the repository at this point in the history
  • Loading branch information
ryaanahmed committed Sep 7, 2023
1 parent 1886034 commit e009c3b
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 69 deletions.
2 changes: 1 addition & 1 deletion assets/locales/fr/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@
},
"9": {
"caption": "Image 9. Denis Diderot et Jean le Rond d'Alembert, L'Encyclopédie, ou dictionnaire raisonné des arts, des sciences, et des métiers (Paris, 1763), vol. 19, 1763, article cartier, planche 1.",
"text": "L'image 9 montre une pièce unique dans laquelle les cartes sont peintes, lustrées, coupées et réparties en différents jeux. Les personnages désignés par les figures 1 et 2 sur la gauche appliquent la peinture en utilisant la technique du pochoir décrite ci-dessus. La figure 3 est le <1>lisseur</1>, qui applique un lustre aux cartes afin de les rendre plus faciles à manipuler et plus agréables au toucher. La figure 4 utilise la grande paire de ciseaux fixée à la table pour découper en cartes individuelles les feuilles séchées et enluminées fournies par la figure 5. Enfin, à l'extrême droite, la figure 6 trie les cartes découpées en jeux individuels. La figure 7, à l'arrière-plan, travaille sur la presse utilisée pour confectionner le papier qui servira de support aux cartes créées dans la pièce avant de l'atelier."
"text": "L'image 9 montre une pièce unique dans laquelle les cartes sont peintes, lustrées, coupées et réparties en différents jeux. Les personnages désignés par les figures 1 et 2 sur la gauche appliquent la peinture en utilisant la technique du pochoir décrite ci-dessus. La figure 3 est le <i>lisseur</i>, qui applique un lustre aux cartes afin de les rendre plus faciles à manipuler et plus agréables au toucher. La figure 4 utilise la grande paire de ciseaux fixée à la table pour découper en cartes individuelles les feuilles séchées et enluminées fournies par la figure 5. Enfin, à l'extrême droite, la figure 6 trie les cartes découpées en jeux individuels. La figure 7, à l'arrière-plan, travaille sur la presse utilisée pour confectionner le papier qui servira de support aux cartes créées dans la pièce avant de l'atelier."
}
},
"material": {
Expand Down
26 changes: 19 additions & 7 deletions backend/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@
'component_name': 'ExampleId'
}
"""
import os
import openai

from random import randint, sample
import json
import os

from django.shortcuts import render
from django.http import JsonResponse
Expand All @@ -35,6 +34,8 @@
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt

import openai

from .models import Card, Deck, Tarot


Expand All @@ -53,14 +54,25 @@ def index(request):
return render(request, 'index.html', context)


@csrf_exempt
def divination_card_request(request):
num = int(request.GET.get('number'))
up = bool(int(request.GET.get('orientation')))
num_cards = int(request.GET.get('num'))
lang = "fr" if "fr" in request.GET.get('language') else "en"

card = Tarot.objects.filter(number__exact=num).filter(lang__exact=lang).get(orientation=up)
# Fetch all Tarot objects with the given language
all_cards = list(Tarot.objects.filter(lang__exact=lang))

# Randomly sample cards
chosen_cards = sample(all_cards, num_cards)

# Add random orientation to each card
for card in chosen_cards:
card.orientation = bool(randint(0, 1))

cards_data = [model_to_dict(card) for card in chosen_cards]

return JsonResponse({'cards': cards_data})

return JsonResponse({'card': model_to_dict(card)})

@csrf_exempt
def generate_prediction(request):
Expand Down
64 changes: 23 additions & 41 deletions frontend/components/DivinationGame.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import React, { useState } from "react";
import axios from "axios";
import i18next from "i18next";
import { useTranslation } from "react-i18next";
import { Container, Row, Col, Form, Alert } from 'react-bootstrap';
import Loading from "./Loading";

axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";

const NUM_CARDS = 33;

const DisclaimerScreen = ({ goToNext }) => {
const { t } = useTranslation();
return (
Expand Down Expand Up @@ -123,7 +117,6 @@ const Screen2 = ({ goToNext }) => {
async function getReading(question, keywords) {
let input = question.trim();


const input_string =
`Generate a cartomancy reading based on the practices of Jean-Baptiste Alliette from the 18th century.
Pretend you are an online cartomancer, interpreting the mystical themes of Alliette's historic teachings.
Expand All @@ -144,19 +137,28 @@ async function getReading(question, keywords) {
Overcome them, and prosperity is assured."`;

try {
console.log("Sending request and waiting...");
let response = await axios({
method: "post",
url: "/generate-prediction/",
data: {
const response = await fetch("/generate-prediction/", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
question: input_string
}
})
});
console.log("Got our response...");
return response.data.response;

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const data = await response.json();
return data.response;
} catch (error) {
console.log(error);
}



}


Expand Down Expand Up @@ -280,35 +282,15 @@ const DivinationGame = () => {
const [keywords, setKeywords] = React.useState("");

async function getCards(num) {
let cardStrings = new Set();

while(cardStrings.size < num) {
let cardNum = Math.floor(Math.random() * (NUM_CARDS)) + 1;
let cardUp = Math.round(Math.random());
cardStrings.add(cardNum + "." + cardUp);
}

const chosenCards = [];

// TODO(ra): this makes a request per card -- simplify to a single request!
for (const cardString of cardStrings) {
let [cardNum, cardUp] = cardString.split(".");
cardNum = parseInt(cardNum);
cardUp = parseInt(cardUp);

let response = await axios.get("/divination-card/", {
params: {
number: cardNum,
orientation: cardUp,
language: i18next.language
}
});
const response = await fetch(`/divination-card/?num=${num}&language=${i18next.language}`);

chosenCards.push(response.data.card);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

setCards(chosenCards);
return chosenCards;
const data = await response.json();
setCards(data.cards);
return data.cards;
};

// TODO: I think we could expose much more richness about the cards in the display
Expand Down
8 changes: 3 additions & 5 deletions frontend/components/ImageBlock.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import PropTypes from 'prop-types';
import React from "react";
import { Row, Col, Figure } from "react-bootstrap";
import { Trans, useTranslation } from "react-i18next";

export const ImageBlock = ({ imgSrc, captionKey, textKey }) => {
const { t } = useTranslation();
import { Trans } from "react-i18next";

export const ImageBlock = ({ imgSrc, captionKey, text }) => {
return (
<>
<Row className="justify-content-center mt-5">
Expand All @@ -25,7 +23,7 @@ export const ImageBlock = ({ imgSrc, captionKey, textKey }) => {
</Figure>
</Col>
<Col xs={12} md={4}>
<p>{t(textKey)}</p>
<p>{text}</p>
</Col>
</Row>
</>
Expand Down
30 changes: 15 additions & 15 deletions frontend/components/pages/Manufacture.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from "react";
import { Container, Row, Col } from "react-bootstrap";
import { useTranslation } from "react-i18next";
import { Trans, useTranslation } from "react-i18next";
import { ImageBlock } from '../ImageBlock';
import { DoubleImageBlock } from '../DoubleImageBlock';

Expand All @@ -25,48 +25,48 @@ const Manufacture = () => {
</Col>
</Row>

<ImageBlock
<ImageBlock
imgSrc="/static/img/manufacture/Image 1.jpg"
captionKey="manufacture.1.caption"
textKey="manufacture.1.text"
text={t("manufacture.1.text")}
/>

<ImageBlock
<ImageBlock
imgSrc="/static/img/manufacture/Image 2.jpg"
captionKey="manufacture.2.caption"
textKey="manufacture.2.text"
text={t("manufacture.2.text")}
/>

<ImageBlock
<ImageBlock
imgSrc="/static/img/manufacture/Image 3.jpg"
captionKey="manufacture.3.caption"
textKey="manufacture.3.text"
text={t("manufacture.3.text")}
/>

<ImageBlock
<ImageBlock
imgSrc="/static/img/manufacture/Image 4.jpg"
captionKey="manufacture.4.caption"
textKey="manufacture.4.text"
text={t("manufacture.4.text")}
/>

<DoubleImageBlock
<DoubleImageBlock
imgSrc1="/static/img/manufacture/Image 5.jpg"
imgSrc2="/static/img/manufacture/Image 6.jpg"
captionKey="manufacture.5-6.caption"
textKey="manufacture.5-6.text"
text={t("manufacture.5-6.text")}
/>

<DoubleImageBlock
<DoubleImageBlock
imgSrc1="/static/img/manufacture/Image 7.jpg"
imgSrc2="/static/img/manufacture/Image 8.jpg"
captionKey="manufacture.7-8.caption"
textKey="manufacture.7-8.text"
text={t("manufacture.7-8.text")}
/>

<ImageBlock
<ImageBlock
imgSrc="/static/img/manufacture/Image 9.jpg"
captionKey="manufacture.9.caption"
textKey="manufacture.9.text"
text={<Trans i18nKey="manufacture.9.text" />}
/>
</Container>
);
Expand Down

0 comments on commit e009c3b

Please sign in to comment.