Spaces:
Runtime error
Runtime error
File size: 2,479 Bytes
f784d15 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
import logging
from flask import Flask, request, jsonify
import os
from wtforms import Form, StringField
from wtforms.validators import DataRequired
from config import model_ckpt, pipe, labels
app = Flask(__name__)
# # configure logging
# logging.basicConfig(
# filename='app.log',
# level=logging.INFO,
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
# )
# logger = logging.getLogger(__name__)
class PredictForm(Form):
text = StringField('text', [DataRequired()])
def predict(text: str) -> dict:
"""
Compute predictions for text.
:param text: str : The text to be analyzed.
:return: dict : A dictionary of predicted language and its score
"""
try:
preds = pipe(text, return_all_scores=True, truncation=True, max_length=128)
if preds:
pred = preds[0]
pred = sorted(pred, key=lambda x: x['score'], reverse=True)
return {labels.get(p["label"],p["label"]): float(p["score"]) for p in pred[:1]}
else:
return {}
except Exception as e:
logger.error("Error processing request: %s", str(e))
return {'error': str(e)}, 500
@app.route('/language', methods=['POST'])
def predict_language():
"""
A Language Prediction API which accepts 'text' as input and return the language of text along with score
---
parameters:
- in: body
name: text
schema:
type: string
required: true
description: The text to be analyzed
responses:
200:
description: A JSON object containing the language and its score
schema:
type: object
400:
description: Invalid request
500:
description: Internal server error
"""
# form = PredictForm(request.form)
# if form.validate():
text = request.json['text']
if not text:
return jsonify({'error': 'Empty text provided'}), 400
result = predict(text)
if result:
return jsonify(result)
else:
return jsonify({'error': 'No predictions found'}), 400
# else:
# return jsonify({'error': 'Invalid input provided'}), 400
if __name__ == '__main__':
log_file = 'app.log'
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.info("Running the app...")
app.run()
|