Ptul2x5 commited on
Commit
c1172a4
·
verified ·
1 Parent(s): 2a3cbdf
Files changed (1) hide show
  1. app.py +14 -195
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import os
2
  import torch
3
  from transformers import AutoTokenizer
4
- from flask import Flask, request, jsonify, render_template, redirect, url_for, flash, session
5
  from flask_login import LoginManager, login_user, logout_user, login_required, current_user
6
  from models import db, User, Feedback
7
  from forms import RegistrationForm, LoginForm
@@ -11,15 +11,8 @@ app = Flask(__name__)
11
 
12
  # Cấu hình
13
  app.config['SECRET_KEY'] = 'your-secret-key-change-this-in-production'
14
- # Tắt CSRF protection để test
15
- app.config['WTF_CSRF_ENABLED'] = False
16
- # Cấu hình session cho Hugging Face Spaces
17
- app.config['SESSION_COOKIE_SECURE'] = False # Cho HTTP
18
- app.config['SESSION_COOKIE_HTTPONLY'] = True
19
- app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
20
- # Sử dụng database persistent cho Hugging Face Spaces
21
- # Sử dụng thư mục workspace để lưu database (persistent across restarts)
22
- db_path = os.path.join(os.getcwd(), 'feedback_analysis.db')
23
  os.makedirs(os.path.dirname(db_path), exist_ok=True)
24
  app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
25
  app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
@@ -59,131 +52,40 @@ print("✅ Model đã sẵn sàng!")
59
  @app.route("/", methods=["GET"])
60
  @login_required
61
  def home():
62
- print("=" * 40)
63
- print("🏠 HOME DEBUG")
64
- print("=" * 40)
65
- print(f"Current user authenticated: {current_user.is_authenticated}")
66
- print(f"Current user ID: {current_user.id if current_user.is_authenticated else 'None'}")
67
- print(f"Current user username: {current_user.username if current_user.is_authenticated else 'None'}")
68
- print(f"Session data: {dict(session)}")
69
- print("=" * 40)
70
- print("🏁 HOME DEBUG END")
71
- print("=" * 40)
72
  return render_template("index.html")
73
 
74
- @app.route("/debug", methods=["GET"])
75
- def debug():
76
- """Debug route để kiểm tra session và database"""
77
- try:
78
- user_count = User.query.count()
79
- users = User.query.all()
80
-
81
- return jsonify({
82
- "current_user_authenticated": current_user.is_authenticated,
83
- "current_user_id": current_user.id if current_user.is_authenticated else None,
84
- "current_user_username": current_user.username if current_user.is_authenticated else None,
85
- "session_data": dict(session),
86
- "database_path": db_path,
87
- "database_exists": os.path.exists(db_path),
88
- "user_count": user_count,
89
- "users": [{"id": u.id, "username": u.username} for u in users]
90
- })
91
- except Exception as e:
92
- return jsonify({"error": str(e)})
93
-
94
  @app.route("/register", methods=["GET", "POST"])
95
  def register():
96
- print("=" * 40)
97
- print("📝 REGISTER DEBUG")
98
- print("=" * 40)
99
- print(f"Request method: {request.method}")
100
- print(f"Current user authenticated: {current_user.is_authenticated}")
101
-
102
  if current_user.is_authenticated:
103
- print("User already authenticated, redirecting to home")
104
  return redirect(url_for('home'))
105
 
106
  form = RegistrationForm()
107
- print(f"Form created: {form}")
108
-
109
  if form.validate_on_submit():
110
- print(f"Form validated successfully")
111
- print(f"Username: {form.username.data}")
112
- print(f"Password: {form.password.data}")
113
-
114
- try:
115
- user = User(username=form.username.data)
116
- user.set_password(form.password.data)
117
- db.session.add(user)
118
- db.session.commit()
119
- print("✅ User created successfully")
120
- flash('Đăng ký thành công! Vui lòng đăng nhập.', 'success')
121
- print("Flash message set: Đăng ký thành công!")
122
- return redirect(url_for('login'))
123
- except Exception as e:
124
- print(f"❌ Error creating user: {e}")
125
- flash('Có lỗi xảy ra khi đăng ký. Vui lòng thử lại.', 'danger')
126
- print("Flash message set: Có lỗi xảy ra khi đăng ký.")
127
- else:
128
- print(f"Form validation failed: {form.errors}")
129
 
130
- print("=" * 40)
131
- print("🏁 REGISTER DEBUG END")
132
- print("=" * 40)
133
  return render_template('register.html', form=form)
134
 
135
  @app.route("/login", methods=["GET", "POST"])
136
  def login():
137
- print("=" * 40)
138
- print("🔐 LOGIN DEBUG")
139
- print("=" * 40)
140
- print(f"Request method: {request.method}")
141
- print(f"Current user authenticated: {current_user.is_authenticated}")
142
-
143
  if current_user.is_authenticated:
144
- print("User already authenticated, redirecting to home")
145
  return redirect(url_for('home'))
146
 
147
  form = LoginForm()
148
- print(f"Form created: {form}")
149
-
150
  if form.validate_on_submit():
151
- print(f"Form validated successfully")
152
- print(f"Username: {form.username.data}")
153
- print(f"Password: {form.password.data}")
154
-
155
  user = User.query.filter_by(username=form.username.data).first()
156
- print(f"User found: {user}")
157
-
158
- if user:
159
- print(f"User exists, checking password...")
160
- password_check = user.check_password(form.password.data)
161
- print(f"Password check result: {password_check}")
162
-
163
- if password_check:
164
- print("Password correct, logging in user")
165
- login_user(user, remember=True)
166
- print(f"User authenticated after login: {current_user.is_authenticated}")
167
- print(f"User ID: {current_user.id}")
168
- print(f"Session data: {dict(session)}")
169
- flash('Đăng nhập thành công!', 'success')
170
- print("Flash message set: Đăng nhập thành công!")
171
- next_page = request.args.get('next')
172
- return redirect(next_page) if next_page else redirect(url_for('home'))
173
- else:
174
- print("Password incorrect")
175
- flash('Tên đăng nhập hoặc mật khẩu không đúng.', 'danger')
176
- print("Flash message set: Tên đăng nhập hoặc mật khẩu không đúng.")
177
  else:
178
- print("User not found")
179
  flash('Tên đăng nhập hoặc mật khẩu không đúng.', 'danger')
180
- print("Flash message set: Tên đăng nhập hoặc mật khẩu không đúng.")
181
- else:
182
- print(f"Form validation failed: {form.errors}")
183
 
184
- print("=" * 40)
185
- print("🏁 LOGIN DEBUG END")
186
- print("=" * 40)
187
  return render_template('login.html', form=form)
188
 
189
  @app.route("/logout")
@@ -197,26 +99,6 @@ def logout():
197
  def health():
198
  return jsonify({"status": "healthy", "message": "✅ PhoBERT MultiTask API is running!"})
199
 
200
- @app.route("/api/users", methods=["GET"])
201
- def get_users():
202
- """API để xem danh sách users (cho admin)"""
203
- try:
204
- users = User.query.all()
205
- user_list = []
206
- for user in users:
207
- user_list.append({
208
- 'id': user.id,
209
- 'username': user.username,
210
- 'created_at': user.created_at.isoformat(),
211
- 'feedback_count': len(user.feedbacks)
212
- })
213
- return jsonify({
214
- 'users': user_list,
215
- 'total': len(user_list)
216
- })
217
- except Exception as e:
218
- return jsonify({"error": f"Có lỗi xảy ra: {str(e)}"}), 500
219
-
220
  @app.route("/api/feedback-history", methods=["GET"])
221
  @login_required
222
  def get_feedback_history():
@@ -317,71 +199,8 @@ def predict():
317
 
318
  # Khởi tạo database
319
  with app.app_context():
320
- print("=" * 60)
321
- print("🔍 DEBUG DATABASE - HUGGING FACE SPACE")
322
- print("=" * 60)
323
-
324
- # Debug: Kiểm tra đường dẫn database
325
- print(f"📁 Current working directory: {os.getcwd()}")
326
- print(f"📁 Database path: {db_path}")
327
- print(f"📁 Database exists: {os.path.exists(db_path)}")
328
- print(f"📁 Instance directory exists: {os.path.exists(os.path.dirname(db_path))}")
329
-
330
- # Debug: Kiểm tra quyền ghi file
331
- try:
332
- test_file = os.path.join(os.getcwd(), 'test_write.txt')
333
- with open(test_file, 'w') as f:
334
- f.write("test")
335
- os.remove(test_file)
336
- print("✅ Có quyền ghi file")
337
- except Exception as e:
338
- print(f"❌ Không có quyền ghi file: {e}")
339
-
340
- # Tạo database
341
  db.create_all()
342
  print("✅ Database đã sẵn sàng!")
343
-
344
- # Debug: Kiểm tra database sau khi tạo
345
- try:
346
- user_count = User.query.count()
347
- print(f"📊 Số lượng users trong database: {user_count}")
348
-
349
- if user_count > 0:
350
- users = User.query.all()
351
- print("👥 Danh sách users:")
352
- for user in users:
353
- print(f" - ID: {user.id}, Username: {user.username}, Created: {user.created_at}")
354
- else:
355
- print("👥 Chưa có user nào, tạo admin user mặc định...")
356
- admin_user = User(username='admin')
357
- admin_user.set_password('admin123')
358
- db.session.add(admin_user)
359
- db.session.commit()
360
- print("✅ Admin user đã được tạo: username=admin, password=admin123")
361
-
362
- # Tạo thêm demo user
363
- demo_user = User(username='demo')
364
- demo_user.set_password('demo123')
365
- db.session.add(demo_user)
366
- db.session.commit()
367
- print("✅ Demo user đã được tạo: username=demo, password=demo123")
368
-
369
- # Debug: Kiểm tra file database
370
- if os.path.exists(db_path):
371
- file_size = os.path.getsize(db_path)
372
- print(f"📁 Database file size: {file_size} bytes")
373
- print(f"📁 Database file path: {db_path}")
374
- else:
375
- print("❌ Database file không tồn tại!")
376
-
377
- except Exception as e:
378
- print(f"❌ Lỗi database: {e}")
379
- import traceback
380
- traceback.print_exc()
381
-
382
- print("=" * 60)
383
- print("🏁 DATABASE DEBUG HOÀN THÀNH")
384
- print("=" * 60)
385
 
386
  if __name__ == "__main__":
387
  # Hugging Face Spaces configuration
 
1
  import os
2
  import torch
3
  from transformers import AutoTokenizer
4
+ from flask import Flask, request, jsonify, render_template, redirect, url_for, flash
5
  from flask_login import LoginManager, login_user, logout_user, login_required, current_user
6
  from models import db, User, Feedback
7
  from forms import RegistrationForm, LoginForm
 
11
 
12
  # Cấu hình
13
  app.config['SECRET_KEY'] = 'your-secret-key-change-this-in-production'
14
+ # Sử dụng đường dẫn database phù hợp với Hugging Face Spaces
15
+ db_path = os.path.join(os.getcwd(), 'instance', 'feedback_analysis.db')
 
 
 
 
 
 
 
16
  os.makedirs(os.path.dirname(db_path), exist_ok=True)
17
  app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
18
  app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
 
52
  @app.route("/", methods=["GET"])
53
  @login_required
54
  def home():
 
 
 
 
 
 
 
 
 
 
55
  return render_template("index.html")
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  @app.route("/register", methods=["GET", "POST"])
58
  def register():
 
 
 
 
 
 
59
  if current_user.is_authenticated:
 
60
  return redirect(url_for('home'))
61
 
62
  form = RegistrationForm()
 
 
63
  if form.validate_on_submit():
64
+ user = User(username=form.username.data)
65
+ user.set_password(form.password.data)
66
+ db.session.add(user)
67
+ db.session.commit()
68
+ flash('Đăng ký thành công! Vui lòng đăng nhập.', 'success')
69
+ return redirect(url_for('login'))
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
 
 
 
71
  return render_template('register.html', form=form)
72
 
73
  @app.route("/login", methods=["GET", "POST"])
74
  def login():
 
 
 
 
 
 
75
  if current_user.is_authenticated:
 
76
  return redirect(url_for('home'))
77
 
78
  form = LoginForm()
 
 
79
  if form.validate_on_submit():
 
 
 
 
80
  user = User.query.filter_by(username=form.username.data).first()
81
+ if user and user.check_password(form.password.data):
82
+ login_user(user, remember=True)
83
+ flash('Đăng nhập thành công!', 'success')
84
+ next_page = request.args.get('next')
85
+ return redirect(next_page) if next_page else redirect(url_for('home'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  else:
 
87
  flash('Tên đăng nhập hoặc mật khẩu không đúng.', 'danger')
 
 
 
88
 
 
 
 
89
  return render_template('login.html', form=form)
90
 
91
  @app.route("/logout")
 
99
  def health():
100
  return jsonify({"status": "healthy", "message": "✅ PhoBERT MultiTask API is running!"})
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  @app.route("/api/feedback-history", methods=["GET"])
103
  @login_required
104
  def get_feedback_history():
 
199
 
200
  # Khởi tạo database
201
  with app.app_context():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  db.create_all()
203
  print("✅ Database đã sẵn sàng!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
  if __name__ == "__main__":
206
  # Hugging Face Spaces configuration