tuan243 commited on
Commit
ba49f6d
·
verified ·
1 Parent(s): 35c0e49

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +106 -89
main.py CHANGED
@@ -1,93 +1,110 @@
1
- from fastapi import FastAPI
2
- from fastapi.responses import JSONResponse
3
- import firebase_admin
4
- from firebase_admin import credentials, firestore
5
- from transformers import pipeline
6
- from pydantic import BaseModel
7
- import os
8
- from huggingface_hub import login
9
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # AutoModelForCausalLM,
10
 
11
- # Load Firebase
12
- cred = credentials.Certificate("firebase_config.json")
13
- firebase_admin.initialize_app(cred)
14
- db = firestore.client()
15
 
16
- # Đăng nhập vào Hugging Face (nếu cần)
17
- HF_TOKEN = os.getenv("HF_TOKEN")
18
- if HF_TOKEN:
19
- login(HF_TOKEN)
20
-
21
- # Load AI Model
22
- tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base",token=HF_TOKEN)
23
- ai_model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-base",token=HF_TOKEN)
24
-
25
- app = FastAPI()
26
-
27
- # Request Models
28
- class UpdateBiosRequest(BaseModel):
29
- user_id: str
30
- bios: str
31
-
32
- class FocusHistoryRequest(BaseModel):
33
- user_id: str
34
- time_start: str
35
- total_time: int
36
-
37
- class AIRequest(BaseModel):
38
- user_id: str
39
-
40
- # API cập nhật bios
41
- @app.post("/update_bios")
42
- async def update_bios(request: UpdateBiosRequest):
43
- user_ref = db.collection("user_profiles").document(request.user_id)
44
- user_ref.set({"bios": request.bios}, merge=True)
45
- return {"message": "Cập nhật bios thành công"}
46
-
47
- # API thêm lịch sử focus
48
- @app.post("/add_focus_history")
49
- async def add_focus_history(request: FocusHistoryRequest):
50
- user_ref = db.collection("user_profiles").document(request.user_id)
51
- user_doc = user_ref.get()
52
- data = user_doc.to_dict() or {}
53
- focus_history = data.get("focus_history", [])
54
- focus_history.append({"time_start": request.time_start, "total_time": request.total_time})
55
- user_ref.set({"focus_history": focus_history}, merge=True)
56
- return {"message": "Thêm lịch sử focus thành công"}
57
-
58
- # API lấy dữ liệu người dùng
59
- @app.get("/get_user_data")
60
- async def get_user_data(user_id: str):
61
- user_doc = db.collection("user_profiles").document(user_id).get()
62
- data = user_doc.to_dict() or {}
63
- return {
64
- "bios": data.get("bios", "Chưa có bios."),
65
- "focus_history": data.get("focus_history", [])
66
- }
67
-
68
- # API AI tư vấn
69
- @app.post("/ai_personal_advice")
70
- async def ai_personal_advice(request: AIRequest):
71
- user_doc = db.collection("user_profiles").document(request.user_id).get()
72
- data = user_doc.to_dict() or {}
73
- bios = data.get("bios", "Chưa có bios.")
74
- focus_history = data.get("focus_history", [])
75
- focus_text = "\n".join([f"- {f['time_start']}: {f['total_time']} phút" for f in focus_history])
76
 
77
- prompt = f"""
78
- Thông tin người dùng:
79
- - Bios: {bios}
80
- - Lịch sử focus:
81
- {focus_text}
82
 
83
- Hãy tư vấn cách cải thiện hiệu suất làm việc dựa trên thông tin trên.
84
- """
85
- input_ids = tokenizer(combined_information, return_tensors="pt")
86
- response = ai_model.generate(**input_ids, max_new_tokens=500)
87
- # response = ai_model(prompt, max_length=200)
88
- return {"advice": tokenizer.decode(response[0])}
89
-
90
- # Trang chủ
91
- @app.get("/")
92
- async def home():
93
- return JSONResponse(content={"message": "Welcome to the Recommendation API!"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from fastapi import FastAPI
2
+ # from fastapi.responses import JSONResponse
3
+ # import firebase_admin
4
+ # from firebase_admin import credentials, firestore
5
+ # from transformers import pipeline
6
+ # from pydantic import BaseModel
7
+ # import os
8
+ # from huggingface_hub import login
9
+ # from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # AutoModelForCausalLM,
10
 
11
+ # # Load Firebase
12
+ # cred = credentials.Certificate("firebase_config.json")
13
+ # firebase_admin.initialize_app(cred)
14
+ # db = firestore.client()
15
 
16
+ # # Đăng nhập vào Hugging Face (nếu cần)
17
+ # HF_TOKEN = os.getenv("HF_TOKEN")
18
+ # if HF_TOKEN:
19
+ # login(HF_TOKEN)
20
+
21
+ # # Load AI Model
22
+ # tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base",token=HF_TOKEN)
23
+ # ai_model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-base",token=HF_TOKEN)
24
+
25
+ # app = FastAPI()
26
+
27
+ # # Request Models
28
+ # class UpdateBiosRequest(BaseModel):
29
+ # user_id: str
30
+ # bios: str
31
+
32
+ # class FocusHistoryRequest(BaseModel):
33
+ # user_id: str
34
+ # time_start: str
35
+ # total_time: int
36
+
37
+ # class AIRequest(BaseModel):
38
+ # user_id: str
39
+
40
+ # # API cập nhật bios
41
+ # @app.post("/update_bios")
42
+ # async def update_bios(request: UpdateBiosRequest):
43
+ # user_ref = db.collection("user_profiles").document(request.user_id)
44
+ # user_ref.set({"bios": request.bios}, merge=True)
45
+ # return {"message": "Cập nhật bios thành công"}
46
+
47
+ # # API thêm lịch sử focus
48
+ # @app.post("/add_focus_history")
49
+ # async def add_focus_history(request: FocusHistoryRequest):
50
+ # user_ref = db.collection("user_profiles").document(request.user_id)
51
+ # user_doc = user_ref.get()
52
+ # data = user_doc.to_dict() or {}
53
+ # focus_history = data.get("focus_history", [])
54
+ # focus_history.append({"time_start": request.time_start, "total_time": request.total_time})
55
+ # user_ref.set({"focus_history": focus_history}, merge=True)
56
+ # return {"message": "Thêm lịch sử focus thành công"}
57
+
58
+ # # API lấy dữ liệu người dùng
59
+ # @app.get("/get_user_data")
60
+ # async def get_user_data(user_id: str):
61
+ # user_doc = db.collection("user_profiles").document(user_id).get()
62
+ # data = user_doc.to_dict() or {}
63
+ # return {
64
+ # "bios": data.get("bios", "Chưa có bios."),
65
+ # "focus_history": data.get("focus_history", [])
66
+ # }
67
+
68
+ # # API AI tư vấn
69
+ # @app.post("/ai_personal_advice")
70
+ # async def ai_personal_advice(request: AIRequest):
71
+ # user_doc = db.collection("user_profiles").document(request.user_id).get()
72
+ # data = user_doc.to_dict() or {}
73
+ # bios = data.get("bios", "Chưa có bios.")
74
+ # focus_history = data.get("focus_history", [])
75
+ # focus_text = "\n".join([f"- {f['time_start']}: {f['total_time']} phút" for f in focus_history])
76
 
77
+ # prompt = f"""
78
+ # Thông tin người dùng:
79
+ # - Bios: {bios}
80
+ # - Lịch sử focus:
81
+ # {focus_text}
82
 
83
+ # Hãy tư vấn cách cải thiện hiệu suất làm việc dựa trên thông tin trên.
84
+ # """
85
+ # input_ids = tokenizer(combined_information, return_tensors="pt")
86
+ # response = ai_model.generate(**input_ids, max_new_tokens=500)
87
+ # # response = ai_model(prompt, max_length=200)
88
+ # return {"advice": tokenizer.decode(response[0])}
89
+
90
+ # # Trang chủ
91
+ # @app.get("/")
92
+ # async def home():
93
+ # return JSONResponse(content={"message": "Welcome to the Recommendation API!"})
94
+
95
+
96
+
97
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
98
+
99
+ # Kiểm tra biến môi trường HF_TOKEN
100
+ import os
101
+ HF_TOKEN = os.getenv("HF_TOKEN")
102
+ print("HF_TOKEN:", HF_TOKEN is not None)
103
+
104
+ # Load model
105
+ model_name = "google/flan-t5-base"
106
+ tokenizer = AutoTokenizer.from_pretrained(model_name, token=HF_TOKEN)
107
+ ai_model = AutoModelForSeq2SeqLM.from_pretrained(model_name, token=HF_TOKEN)
108
+
109
+ print("Model loaded successfully!")
110
+