bambadij commited on
Commit
40d6b91
·
verified ·
1 Parent(s): 7d971c7
Files changed (1) hide show
  1. app.py +73 -117
app.py CHANGED
@@ -1,125 +1,81 @@
1
- from fastapi import FastAPI, Depends, HTTPException, status
2
- from sqlalchemy.orm import Session
3
- from sqlalchemy import create_engine, Column, Integer, String, Boolean, Enum
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
- app =FastAPI(
18
- title='API kitty',
19
- description ='Informations'
20
- )
21
- app.add_middleware(
22
- CORSMiddleware,
23
- allow_origins=["*"],
24
- allow_credentials=True,
25
- allow_methods=["*"],
26
- allow_headers=["*"],
27
  )
28
 
29
- # Configuration JWT et hachage de mot de passe
30
- SECRET_KEY = "your_secret_key"
31
- ALGORITHM = "HS256"
32
- ACCESS_TOKEN_EXPIRE_MINUTES = 30
33
-
34
- pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
35
-
36
- # Modèle pour les utilisateurs
37
- class User(Base):
38
- __tablename__ = "users"
39
- id = Column(Integer, primary_key=True, index=True)
40
- name = Column(String(255), unique=True, index=True)
41
- passcode = Column(String(255))
42
- accept_terms = Column(Boolean)
43
- sex = Column(Enum('male', 'female'))
44
- age = Column(Integer)
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
- # Schéma de données pour l'authentification
82
- class Token(BaseModel):
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
- # Connexion d'un utilisateur
101
- @app.post("/login/", response_model=Token)
102
- def login(user: UserLogin, db: Session = Depends(get_db)):
103
- db_user = db.query(User).filter(User.name == user.name).first()
104
- if not db_user:
105
- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
106
- if not verify_password(user.passcode, db_user.passcode):
107
- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
108
-
109
- access_token = create_access_token(data={"sub": db_user.name})
110
- return {"access_token": access_token, "token_type": "bearer"}
 
 
 
 
 
 
 
 
 
 
111
 
112
- # API protégée utilisant OpenAI après connexion
113
- @app.post("/use_openai/")
114
- def use_openai(db: Session = Depends(get_db), token: str = Depends(create_access_token)):
115
- # Appel à l'API OpenAI en utilisant la clé d'accès
116
- openai.api_key = "YOUR_OPENAI_API_KEY"
117
-
118
- # Exemple de requête OpenAI
119
- response = openai.Completion.create(
120
- engine="text-davinci-003",
121
- prompt="Hello, how are you?",
122
- max_tokens=50
123
- )
124
-
125
- return {"openai_response": response["choices"][0]["text"].strip()}
 
 
 
 
 
 
 
 
 
 
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)