Spaces:
Sleeping
Sleeping
update
Browse files
app.py
CHANGED
@@ -1,125 +1,81 @@
|
|
1 |
-
from fastapi import FastAPI,
|
2 |
-
from
|
3 |
-
from
|
4 |
-
from sqlalchemy.ext.declarative import declarative_base
|
5 |
-
from sqlalchemy.orm import sessionmaker
|
6 |
-
from passlib.context import CryptContext
|
7 |
-
from jose import JWTError, jwt
|
8 |
-
import openai
|
9 |
-
from fastapi.middleware.cors import CORSMiddleware
|
10 |
-
|
11 |
-
# Configuration de la base de données MySQL
|
12 |
-
DATABASE_URL = "mysql+mysqlconnector://basa6167_kity_cara:4P&l-5yH1Ql8@https://kumquat.o2switch.net:2083/basa6167_kitty"
|
13 |
-
engine = create_engine(DATABASE_URL)
|
14 |
-
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
15 |
-
Base = declarative_base()
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
app.add_middleware(
|
22 |
-
CORSMiddleware,
|
23 |
-
allow_origins=["*"],
|
24 |
-
allow_credentials=True,
|
25 |
-
allow_methods=["*"],
|
26 |
-
allow_headers=["*"],
|
27 |
)
|
28 |
|
29 |
-
#
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
Base.metadata.create_all(bind=engine)
|
47 |
-
|
48 |
-
app = FastAPI()
|
49 |
-
|
50 |
-
# Créer une session pour la base de données
|
51 |
-
def get_db():
|
52 |
-
db = SessionLocal()
|
53 |
-
try:
|
54 |
-
yield db
|
55 |
-
finally:
|
56 |
-
db.close()
|
57 |
-
|
58 |
-
# Fonction pour vérifier le mot de passe haché
|
59 |
-
def verify_password(plain_password, hashed_password):
|
60 |
-
return pwd_context.verify(plain_password, hashed_password)
|
61 |
-
|
62 |
-
# Fonction pour hacher le mot de passe
|
63 |
-
def get_password_hash(password):
|
64 |
-
return pwd_context.hash(password)
|
65 |
-
|
66 |
-
# Fonction pour créer un JWT token
|
67 |
-
def create_access_token(data: dict):
|
68 |
-
to_encode = data.copy()
|
69 |
-
token = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
70 |
-
return token
|
71 |
-
|
72 |
-
# Schéma de données pour la création d'utilisateurs
|
73 |
-
from pydantic import BaseModel
|
74 |
-
class UserCreate(BaseModel):
|
75 |
name: str
|
76 |
-
passcode: str
|
77 |
-
accept_terms: bool
|
78 |
-
sex: str
|
79 |
age: int
|
|
|
|
|
|
|
|
|
80 |
|
81 |
-
#
|
82 |
-
|
83 |
-
access_token: str
|
84 |
-
token_type: str
|
85 |
-
|
86 |
-
class UserLogin(BaseModel):
|
87 |
-
name: str
|
88 |
-
passcode: str
|
89 |
-
|
90 |
-
# Inscription d'un utilisateur
|
91 |
-
@app.post("/register/")
|
92 |
-
def register(user: UserCreate, db: Session = Depends(get_db)):
|
93 |
-
hashed_password = get_password_hash(user.passcode)
|
94 |
-
db_user = User(name=user.name, passcode=hashed_password, accept_terms=user.accept_terms, sex=user.sex, age=user.age)
|
95 |
-
db.add(db_user)
|
96 |
-
db.commit()
|
97 |
-
db.refresh(db_user)
|
98 |
-
return {"message": "User registered successfully"}
|
99 |
|
100 |
-
#
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from openai import OpenAI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
+
# Initialiser le client OpenAI
|
6 |
+
client = OpenAI(
|
7 |
+
base_url="https://integrate.api.nvidia.com/v1",
|
8 |
+
api_key="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"
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
)
|
10 |
|
11 |
+
# Définir les prompts
|
12 |
+
DEFAULT_PROMPT2 = """You are Kittycara, a friendly AI assistant designed to help adolescent girls and their caretakers understand menstrual health.
|
13 |
+
Your goal is to provide support, information, and potential diagnoses based on the symptoms provided. Remember to be sensitive, supportive, and
|
14 |
+
encourage seeking professional medical advice when necessary. Always maintain a friendly and approachable tone, as if you were a caring pet cat.
|
15 |
+
Always explain medical terms in a way that is easy to understand. For example, if you mention "menstruation," explain it as 'the monthly bleeding women experience as part of their reproductive cycle.'
|
16 |
+
If asked about topics outside of menstrual health or medical information, politely state that you're not able to discuss those subjects
|
17 |
+
and redirect the conversation to menstrual health concerns. Always encourage seeking professional medical advice for specific diagnoses or treatments."""
|
18 |
+
|
19 |
+
SYMPTOMS = [
|
20 |
+
"Heavy bleeding", "Irregular periods", "Painful periods", "Missed periods",
|
21 |
+
"Spotting between periods", "Mood swings", "Fatigue", "Abdominal pain",
|
22 |
+
"Nausea", "Headaches", "Breast tenderness", "Acne"
|
23 |
+
]
|
24 |
+
|
25 |
+
# Définir les classes de données d'entrée avec Pydantic
|
26 |
+
class RequestData(BaseModel):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
name: str
|
|
|
|
|
|
|
28 |
age: int
|
29 |
+
sex: str
|
30 |
+
message: str
|
31 |
+
history: list
|
32 |
+
symptoms: list
|
33 |
|
34 |
+
# Initialiser l'application FastAPI
|
35 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
+
# Fonction pour obtenir un message personnalisé basé sur les symptômes
|
38 |
+
def get_reassurance_message(symptoms):
|
39 |
+
if "Painful periods" in symptoms or "Abdominal pain" in symptoms:
|
40 |
+
return "I know that pain can be tough, but you're doing great, and it's important to listen to your body. 🫂 Take care, and don't hesitate to reach out to a healthcare professional!"
|
41 |
+
elif "Mood swings" in symptoms or "Fatigue" in symptoms:
|
42 |
+
return "It's completely normal to feel this way sometimes. Don't worry, you're not alone, and things will get better. 🌼 Stay strong!"
|
43 |
+
elif "Heavy bleeding" in symptoms:
|
44 |
+
return "Heavy bleeding can be concerning, but there are options to help manage it. 🧡 It’s always good to talk to a doctor to make sure everything's okay."
|
45 |
+
else:
|
46 |
+
return "You're doing great by paying attention to your health. 💪 Keep going, and don't hesitate to ask for help if you need it!"
|
47 |
+
|
48 |
+
# Fonction pour prédire la réponse
|
49 |
+
def predict(name, age, sex, message, history, symptoms):
|
50 |
+
messages = [{"role": "system", "content": DEFAULT_PROMPT2}]
|
51 |
+
for human, assistant in history:
|
52 |
+
messages.append({"role": "user", "content": human})
|
53 |
+
messages.append({"role": "assistant", "content": assistant})
|
54 |
+
|
55 |
+
selected_symptoms = ", ".join([sym for sym in symptoms if sym])
|
56 |
+
full_message = f"Name: {name}, Age: {age}, Sex: {sex}\nSymptoms: {selected_symptoms}\nAdditional information: {message}"
|
57 |
+
messages.append({"role": "user", "content": full_message})
|
58 |
|
59 |
+
try:
|
60 |
+
completion = client.chat.completions.create(
|
61 |
+
model="meta/llama-3.1-8b-instruct",
|
62 |
+
messages=messages,
|
63 |
+
temperature=0.2,
|
64 |
+
top_p=0.9,
|
65 |
+
max_tokens=1024,
|
66 |
+
stream=True
|
67 |
+
)
|
68 |
+
|
69 |
+
full_response = ""
|
70 |
+
for chunk in completion:
|
71 |
+
if chunk.choices[0].delta.content is not None:
|
72 |
+
full_response += chunk.choices[0].delta.content
|
73 |
+
|
74 |
+
return full_response
|
75 |
+
except Exception as e:
|
76 |
+
return f"Erreur : {str(e)}"
|
77 |
+
|
78 |
+
# Point de départ pour lancer l'application FastAPI avec Uvicorn
|
79 |
+
if __name__ == "__main__":
|
80 |
+
import uvicorn
|
81 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|