0x-YuAN commited on
Commit
dc416dd
·
verified ·
1 Parent(s): 8d3b4be

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +170 -0
app.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Flask backend for the chat assistance website.
3
+
4
+ This application provides API endpoints for processing chat screenshots,
5
+ manual text input, and generating response suggestions.
6
+ """
7
+ import os
8
+ import base64
9
+ import json
10
+ from flask import Flask, request, jsonify, send_file
11
+ from flask_cors import CORS
12
+ from dotenv import load_dotenv
13
+ from img2chat import img2chat
14
+ from chat_analysis import get_suggestion
15
+
16
+ # Load environment variables
17
+ load_dotenv()
18
+
19
+ # Initialize Flask app
20
+ app = Flask(__name__)
21
+ CORS(app) # Enable CORS for all routes
22
+
23
+ # Configure max content length
24
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max upload size
25
+
26
+ ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
27
+
28
+ def allowed_file(filename):
29
+ """Check if the file extension is allowed"""
30
+ return '.' in filename and \
31
+ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
32
+
33
+ def generate_response(chat_text):
34
+ """
35
+ Generate response suggestions based on chat text.
36
+
37
+ Uses the get_suggestion function from chat_analysis.py to generate
38
+ response suggestions based on the provided chat text.
39
+
40
+ Args:
41
+ chat_text (str): The chat text to analyze
42
+
43
+ Returns:
44
+ dict: Analysis and response suggestions
45
+ """
46
+ # Get suggestion from chat_analysis module
47
+ suggestion_text = get_suggestion(chat_text)
48
+
49
+ # Parse the XML response to extract suggestion and example
50
+ # The response format is expected to be:
51
+ # <suggestion>Suggestion text</suggestion><example>Example text</example>
52
+
53
+ analysis = "分析中..."
54
+ suggestion = suggestion_text
55
+
56
+ # Simple parsing of XML tags (could be improved with proper XML parsing)
57
+ if "<suggestion>" in suggestion_text and "</suggestion>" in suggestion_text:
58
+ start_idx = suggestion_text.find("<suggestion>") + len("<suggestion>")
59
+ end_idx = suggestion_text.find("</suggestion>")
60
+ analysis = suggestion_text[start_idx:end_idx].strip()
61
+
62
+ if "<example>" in suggestion_text and "</example>" in suggestion_text:
63
+ start_idx = suggestion_text.find("<example>") + len("<example>")
64
+ end_idx = suggestion_text.find("</example>")
65
+ suggestion = suggestion_text[start_idx:end_idx].strip()
66
+
67
+ return {
68
+ "analysis": analysis,
69
+ "suggestion": suggestion
70
+ }
71
+
72
+ @app.route('/', methods=['GET'])
73
+ def index():
74
+ """Serve the main HTML page"""
75
+ return send_file('index.html')
76
+
77
+ @app.route('/api/health', methods=['GET'])
78
+ def health_check():
79
+ """Health check endpoint"""
80
+ return jsonify({"status": "ok"})
81
+
82
+ @app.route('/api/process-image', methods=['POST'])
83
+ def process_image():
84
+ """
85
+ Process a chat screenshot and return analysis and suggestions.
86
+
87
+ Accepts an image file or a base64 encoded image string.
88
+ """
89
+ try:
90
+ # Check if the post request has the file part
91
+ if 'file' in request.files:
92
+ file = request.files['file']
93
+ if file.filename == '':
94
+ return jsonify({"error": "No selected file"}), 400
95
+
96
+ if file and allowed_file(file.filename):
97
+ # Read file data directly and convert to base64
98
+ file_data = file.read()
99
+ base64_image = base64.b64encode(file_data).decode('utf-8')
100
+
101
+ # Get file extension
102
+ file_ext = file.filename.rsplit('.', 1)[1].lower()
103
+ image_url = f"data:image/{file_ext};base64,{base64_image}"
104
+
105
+ # Process the image
106
+ chat_text = img2chat(image_url)
107
+
108
+ # Generate response suggestions
109
+ response_data = generate_response(chat_text)
110
+
111
+ # Return the results
112
+ return jsonify({
113
+ "chat_text": chat_text,
114
+ "analysis": response_data["analysis"],
115
+ "suggestion": response_data["suggestion"]
116
+ })
117
+ else:
118
+ return jsonify({"error": "File type not allowed"}), 400
119
+
120
+ # Check if base64 image was provided
121
+ elif 'image_data' in request.json:
122
+ image_data = request.json['image_data']
123
+
124
+ # Process the image
125
+ chat_text = img2chat(image_data)
126
+
127
+ # Generate response suggestions
128
+ response_data = generate_response(chat_text)
129
+
130
+ # Return the results
131
+ return jsonify({
132
+ "chat_text": chat_text,
133
+ "analysis": response_data["analysis"],
134
+ "suggestion": response_data["suggestion"]
135
+ })
136
+
137
+ else:
138
+ return jsonify({"error": "No image provided"}), 400
139
+
140
+ except Exception as e:
141
+ return jsonify({"error": str(e)}), 500
142
+
143
+ @app.route('/api/process-text', methods=['POST'])
144
+ def process_text():
145
+ """
146
+ Process manually entered chat text and return analysis and suggestions.
147
+ """
148
+ try:
149
+ data = request.json
150
+
151
+ if not data or 'chat_text' not in data:
152
+ return jsonify({"error": "No chat text provided"}), 400
153
+
154
+ chat_text = data['chat_text']
155
+
156
+ # Generate response suggestions
157
+ response_data = generate_response(chat_text)
158
+
159
+ # Return the results
160
+ return jsonify({
161
+ "analysis": response_data["analysis"],
162
+ "suggestion": response_data["suggestion"]
163
+ })
164
+
165
+ except Exception as e:
166
+ return jsonify({"error": str(e)}), 500
167
+
168
+ if __name__ == '__main__':
169
+ port = int(os.environ.get('PORT', 8080))
170
+ app.run(host='0.0.0.0', port=port, debug=True)