TDN-M commited on
Commit
a6793d5
·
verified ·
1 Parent(s): fbd6d1a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -73
app.py CHANGED
@@ -1,38 +1,26 @@
1
  import os
2
- import gradio as gr
3
- from langchain.chat_models import ChatOpenAI
4
- from langchain import LLMChain, PromptTemplate
5
- from langchain.memory import ConversationBufferMemory
6
  import openai
7
  from docx import Document
8
  from fpdf import FPDF
 
 
 
9
 
10
- # Lấy API key từ biến môi trường
11
- OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
12
-
13
- template = """You are a very helpful assistant in providing users with information and knowledge about statistics. Additionally, you are also an expert in translating specialized documents on statistics, artificial intelligence, and technology from foreign languages into Vietnamese in a complete, coherent manner while ensuring the original knowledge from the foreign documents is accurately conveyed.
14
- {chat_history}
15
- User: {user_message}
16
- Chatbot:"""
17
-
18
- prompt = PromptTemplate(
19
- input_variables=["chat_history", "user_message"], template=template
20
- )
21
-
22
- memory = ConversationBufferMemory(memory_key="chat_history")
23
 
24
- llm_chain = LLMChain(
25
- llm=ChatOpenAI(temperature=0.5, model_name="gpt-4"),
26
- prompt=prompt,
27
- verbose=True,
28
- memory=memory,
29
- )
30
-
31
- def get_text_response(user_message, chat_history):
32
- response = llm_chain.predict(user_message=user_message)
33
- return response
34
-
35
- def translate_text(text):
36
  prompt = f"Translate the following text to Vietnamese: {text}"
37
  response = openai.Completion.create(
38
  engine="gpt-4",
@@ -40,15 +28,22 @@ def translate_text(text):
40
  max_tokens=150
41
  )
42
  translation = response.choices[0].text.strip()
43
- return translation
 
 
 
 
 
 
 
44
 
45
- def create_text_file(text, filename, file_format):
46
  if file_format == 'docx':
47
  doc = Document()
48
  doc.add_paragraph(text)
49
  doc_path = f"{filename}.docx"
50
  doc.save(doc_path)
51
- return doc_path
 
52
  elif file_format == 'pdf':
53
  pdf = FPDF()
54
  pdf.add_page()
@@ -56,46 +51,35 @@ def create_text_file(text, filename, file_format):
56
  pdf.multi_cell(0, 10, text)
57
  pdf_path = f"{filename}.pdf"
58
  pdf.output(pdf_path)
59
- return pdf_path
60
-
61
- def chatbot_interface():
62
- with gr.Blocks() as demo:
63
- chatbot = gr.Chatbot()
64
- msg = gr.Textbox(placeholder="Nhập tin nhắn...")
65
- clear = gr.Button("Xóa hội thoại")
66
- translate_input = gr.Textbox(placeholder="Nhập văn bản để dịch...")
67
- translate_button = gr.Button("Dịch sang tiếng Việt")
68
- translate_output = gr.Textbox(label="Bản dịch")
69
- file_text = gr.Textbox(placeholder="Nhập văn bản để tạo file...")
70
- file_name = gr.Textbox(placeholder="Nhập tên file (không bao gồm đuôi)...")
71
- file_format = gr.Dropdown(choices=["docx", "pdf"], label="Chọn định dạng file")
72
- create_file_button = gr.Button("Tạo File")
73
- download = gr.File(label="Tải về file", interactive=False)
74
-
75
- def respond(message, chat_history):
76
- response = get_text_response(message, chat_history)
77
- chat_history.append(("Người dùng", message))
78
- chat_history.append(("Chatbot", response))
79
- return chat_history, chat_history
80
-
81
- def clear_chat():
82
- return [], []
83
-
84
- def translate_and_display(text):
85
- translation = translate_text(text)
86
- return translation
87
-
88
- def create_and_return_file(text, name, format):
89
- file_path = create_text_file(text, name, format)
90
- return file_path
91
-
92
- msg.submit(respond, [msg, chatbot], [chatbot, chatbot])
93
- clear.click(clear_chat, [], [chatbot])
94
- translate_button.click(translate_and_display, [translate_input], [translate_output])
95
- create_file_button.click(create_and_return_file, [file_text, file_name, file_format], [download])
96
-
97
- return demo
98
 
99
  if __name__ == "__main__":
100
- demo = chatbot_interface()
101
- demo.launch()
 
1
  import os
2
+ from flask import Flask, request, jsonify, send_file
3
+ from flask_cors import CORS
 
 
4
  import openai
5
  from docx import Document
6
  from fpdf import FPDF
7
+ import smtplib
8
+ from email.mime.text import MIMEText
9
+ from email.mime.multipart import MIMEMultipart
10
 
11
+ app = Flask(__name__)
12
+ CORS(app)
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ # Lấy API key từ biến môi trường
15
+ openai.api_key = os.getenv('OPENAI_API_KEY')
16
+
17
+ @app.route('/translate', methods=['POST'])
18
+ def translate():
19
+ data = request.json
20
+ text = data.get('text')
21
+ target_language = 'vi' # Dịch sang tiếng Việt
22
+
23
+ # Sử dụng OpenAI API để dịch
 
 
24
  prompt = f"Translate the following text to Vietnamese: {text}"
25
  response = openai.Completion.create(
26
  engine="gpt-4",
 
28
  max_tokens=150
29
  )
30
  translation = response.choices[0].text.strip()
31
+ return jsonify({"translation": translation})
32
+
33
+ @app.route('/create_file', methods=['POST'])
34
+ def create_file():
35
+ data = request.json
36
+ text = data.get('text')
37
+ filename = data.get('filename')
38
+ file_format = data.get('file_format')
39
 
 
40
  if file_format == 'docx':
41
  doc = Document()
42
  doc.add_paragraph(text)
43
  doc_path = f"{filename}.docx"
44
  doc.save(doc_path)
45
+ return send_file(doc_path, as_attachment=True)
46
+
47
  elif file_format == 'pdf':
48
  pdf = FPDF()
49
  pdf.add_page()
 
51
  pdf.multi_cell(0, 10, text)
52
  pdf_path = f"{filename}.pdf"
53
  pdf.output(pdf_path)
54
+ return send_file(pdf_path, as_attachment=True)
55
+
56
+ @app.route('/send_email', methods=['POST'])
57
+ def send_email():
58
+ data = request.json
59
+ subject = data.get('subject')
60
+ body = data.get('body')
61
+ to_email = data.get('to_email')
62
+
63
+ # Thông tin đăng nhập email
64
+ from_email = os.getenv('EMAIL_USER')
65
+ email_password = os.getenv('EMAIL_PASS')
66
+
67
+ msg = MIMEMultipart()
68
+ msg['From'] = from_email
69
+ msg['To'] = to_email
70
+ msg['Subject'] = subject
71
+ msg.attach(MIMEText(body, 'plain'))
72
+
73
+ try:
74
+ server = smtplib.SMTP('smtp.gmail.com', 587)
75
+ server.starttls()
76
+ server.login(from_email, email_password)
77
+ text = msg.as_string()
78
+ server.sendmail(from_email, to_email, text)
79
+ server.quit()
80
+ return jsonify({"message": "Email sent successfully"})
81
+ except Exception as e:
82
+ return jsonify({"message": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
83
 
84
  if __name__ == "__main__":
85
+ app.run(host='0.0.0.0', port=5000)