|
import os |
|
from flask import Flask, request, jsonify, send_file |
|
from flask_cors import CORS |
|
import openai |
|
from docx import Document |
|
from fpdf import FPDF |
|
import smtplib |
|
from email.mime.text import MIMEText |
|
from email.mime.multipart import MIMEMultipart |
|
|
|
app = Flask(__name__) |
|
CORS(app) |
|
|
|
|
|
openai.api_key = os.getenv('OPENAI_API_KEY') |
|
|
|
@app.route('/translate', methods=['POST']) |
|
def translate(): |
|
data = request.json |
|
text = data.get('text') |
|
target_language = 'vi' |
|
|
|
|
|
prompt = f"Translate the following text to Vietnamese: {text}" |
|
response = openai.Completion.create( |
|
engine="gpt-4", |
|
prompt=prompt, |
|
max_tokens=150 |
|
) |
|
translation = response.choices[0].text.strip() |
|
return jsonify({"translation": translation}) |
|
|
|
@app.route('/create_file', methods=['POST']) |
|
def create_file(): |
|
data = request.json |
|
text = data.get('text') |
|
filename = data.get('filename') |
|
file_format = data.get('file_format') |
|
|
|
if file_format == 'docx': |
|
doc = Document() |
|
doc.add_paragraph(text) |
|
doc_path = f"{filename}.docx" |
|
doc.save(doc_path) |
|
return send_file(doc_path, as_attachment=True) |
|
|
|
elif file_format == 'pdf': |
|
pdf = FPDF() |
|
pdf.add_page() |
|
pdf.set_font("Arial", size=12) |
|
pdf.multi_cell(0, 10, text) |
|
pdf_path = f"{filename}.pdf" |
|
pdf.output(pdf_path) |
|
return send_file(pdf_path, as_attachment=True) |
|
|
|
@app.route('/send_email', methods=['POST']) |
|
def send_email(): |
|
data = request.json |
|
subject = data.get('subject') |
|
body = data.get('body') |
|
to_email = data.get('to_email') |
|
|
|
|
|
from_email = os.getenv('EMAIL_USER') |
|
email_password = os.getenv('EMAIL_PASS') |
|
|
|
msg = MIMEMultipart() |
|
msg['From'] = from_email |
|
msg['To'] = to_email |
|
msg['Subject'] = subject |
|
msg.attach(MIMEText(body, 'plain')) |
|
|
|
try: |
|
server = smtplib.SMTP('smtp.gmail.com', 587) |
|
server.starttls() |
|
server.login(from_email, email_password) |
|
text = msg.as_string() |
|
server.sendmail(from_email, to_email, text) |
|
server.quit() |
|
return jsonify({"message": "Email sent successfully"}) |
|
except Exception as e: |
|
return jsonify({"message": str(e)}), 500 |
|
|
|
if __name__ == "__main__": |
|
app.run(host='0.0.0.0', port=5000) |
|
|