beanbox-apis / app.py
johnpaulbin's picture
Update app.py
bf57602
raw
history blame
3.12 kB
from flask import Flask, request, jsonify
import asyncio
from hypercorn.asyncio import serve
from hypercorn.config import Config
import os
os.environ['CURL_CA_BUNDLE'] = ''
from googletranslate import translate
import json
import random
app = Flask(__name__)
@app.route('/', methods=['GET'])
def home():
return "HI! Use /translate POST"
# Load the JSON data into memory
def load_json_data(file_path):
with open(file_path, 'r') as file:
data = json.load(file)
return data
# Assuming your JSON structure is a list of dictionaries
json_data = load_json_data('englishspanishpairs.json')
@app.route('/spanish')
def random_spanish_pair():
# Select a random English-Spanish pair
random_pair = random.choice(json_data)
return jsonify(random_pair)
def get_distractors(target_word, all_words, num_distractors=3):
"""
Get distractor words.
'target_word' is the correct word,
'all_words' is a list of words to pick distractors from,
and 'num_distractors' is the number of distractors to return.
"""
distractors = set()
while len(distractors) < num_distractors:
distractor = random.choice(all_words)
if distractor.lower() != target_word.lower():
distractors.add(distractor)
return list(distractors)
@app.route('/fillgame')
def random_spanish_pairfillintheblank():
# Select a random English-Spanish pair
random_pair = random.choice(json_data)
# Choose either English or Spanish for the fill-in-the-blank game
if random.choice([True, False]):
sentence = random_pair['english']
language = 'english'
else:
sentence = random_pair['spanish']
language = 'spanish'
# Split the sentence into words
words = re.findall(r'\b\w+\b', sentence)
# Choose a random word to replace with blank
blank_word = random.choice(words)
sentence_with_blank = sentence.replace(blank_word, "_____")
# Collect all words across sentences for distractors (you might want to customize this)
all_words = [word for pair in json_data for word in re.findall(r'\b\w+\b', pair[language])]
# Get distractors
distractors = get_distractors(blank_word, all_words)
# Combine correct word with distractors and shuffle
options = [blank_word] + distractors
random.shuffle(options)
# Return the sentence with a blank, options, and the correct word
return jsonify({
'sentence': sentence_with_blank,
'options': options,
'correctWord': blank_word,
'language': language
})
@app.route('/translate', methods=['POST'])
def dotranslate():
data = request.get_json()
txt = data.get('txt')
src = data.get('src', 'en')
dest = data.get('dest', 'es')
if txt:
translation = translate(txt, dest=dest, src=src)
return jsonify({'translation': translation}), 200
else:
return jsonify({'error': 'No text provided'}), 400
if __name__ == "__main__":
config = Config()
config.bind = ["0.0.0.0:7860"] # You can specify the host and port here
asyncio.run(serve(app, config))