File size: 4,669 Bytes
b1d0f3b
 
 
 
 
 
 
c653641
 
 
 
b1d0f3b
 
6a0c0af
b1d0f3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4deb4e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1d0f3b
 
4deb4e8
b1d0f3b
4deb4e8
 
b1d0f3b
4deb4e8
 
b1d0f3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import tensorflow as tf
from pydantic import BaseModel
from typing import List
from fastapi import FastAPI
import numpy as np
import requests
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
from keras.models import load_model


model = load_model('models/big5_gru.h5')

class PersonalityRequest(BaseModel):
    responses: List[float] 

class PersonalityResponse(BaseModel):
    personality_type: int 
    personality_name: str

personality_mapping = {
    0: 'Extroverted',
    1: 'Neurotic',
    2: 'Agreeable',
    3: 'Conscientious',
    4: 'Open'
}

origins = ["*"]

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

def five2one(item):
    return (item - 0) / (5 - 0)

model_List = ["gpt-4", "gpt-4-0613", "gpt-3.5-turbo-16k-0613", "gpt-3.5-long"]

def get_response(model, prompt):
    url = "https://gptapi.lumaticai.com/v1/chat/completions"
    body = {
        "model": model,
        "stream": False,
        "messages": [
            {"role": "assistant", "content": prompt}
        ]
    }

    try:
        json_response = requests.post(url, json=body).json().get('choices', [])
        print(model)
        for choice in json_response:
            # print(choice.get('message', {}).get('content', ''))
            res = choice.get('message', {}).get('content', '')
            return res
    except Exception as e:
        # print('Error : ', e)
        return e

def get_response_with_fallback(prompt):
  for model in model_List:
    try:
      response = get_response(model, prompt)
      if not isinstance(response, Exception):  # Check if it's an error
        return {"response": response, "model": model}
    except Exception as e:
      return f"Error with model {model}: {e}"
  # If none succeed, return an error message
  return "Failed to generate diagnosis with any model."


def preprocess_data(new_data_path):
    # Load new data
    new_data = pd.DataFrame(new_data_path)
    
    # Scale the data using the same scaler used during training
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(new_data)
    
    # Reshape the data to fit the model input
    reshaped_data = scaled_data.reshape((scaled_data.shape[1], scaled_data.shape[0], 1))
    
    return reshaped_data

def predict_clusters(model, preprocessed_data):
    # Predict the cluster for each instance
    predictions = model.predict(preprocessed_data)
    
    # Get the cluster with the highest probability
    predicted_clusters = np.argmax(predictions, axis=1)
    
    return predicted_clusters

@app.post("/predict", response_model=PersonalityResponse)
def predict_personality(request: PersonalityRequest):
    preprocessed_data = preprocess_data(request.responses)

    predicted_clusters = predict_clusters(model, preprocessed_data)
    personality_type = predicted_clusters[0]
    
    personality_name = personality_mapping[predicted_clusters[0]]
    print(personality_name)
    
    return PersonalityResponse(personality_type=personality_type, personality_name=personality_name)

@app.post('/personality/description')
def personality_description(personality_name : str):
    prompt = f"\nYou are an psychology expert. I will give you a personality name based on The Big Five OCEAN Personality types. you will provide me with the description of the personality, tell everything about the personality type and the person who have this type of personality. \nPersonality type: {personality_name}. Answer in this format: \nPersonality description: "

    try:
        resultt = get_response_with_fallback(prompt)

        modell = resultt.get('model')

        resultsj = resultt.get('response')

        results = str(resultsj)

        # rst = resultt.response

        if isinstance(results, Exception):
            return {"message": "Error generating diagnosis: " + results, "model": modell}
        
        for line in results.split('\n'):
            if line.startswith('"**Personality description:'):
                ps = line.split(':**')[1].strip()
            elif line.startswith('**Personality description:'):
                ps = line.split(':**')[1].strip()
            elif line.startswith('Personality description:'):
                ps = line.split(':')[1].strip()
        
        return ps

    except Exception as e:
        return {"message": "couldn't get description for " + personality_name}



if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)