Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,125 +1,125 @@
|
|
1 |
-
import tensorflow as tf
|
2 |
-
from tensorflow.keras.models import load_model
|
3 |
-
from pydantic import BaseModel
|
4 |
-
from typing import List
|
5 |
-
from fastapi import FastAPI
|
6 |
-
import numpy as np
|
7 |
-
import requests
|
8 |
-
from fastapi.middleware.cors import CORSMiddleware
|
9 |
-
|
10 |
-
|
11 |
-
model = load_model('models\\big5_gru.h5')
|
12 |
-
|
13 |
-
class PersonalityRequest(BaseModel):
|
14 |
-
responses: List[float]
|
15 |
-
|
16 |
-
class PersonalityResponse(BaseModel):
|
17 |
-
personality_type: int
|
18 |
-
personality_name: str
|
19 |
-
|
20 |
-
personality_mapping = {
|
21 |
-
0: 'Extroverted',
|
22 |
-
1: 'Neurotic',
|
23 |
-
2: 'Agreeable',
|
24 |
-
3: 'Conscientious',
|
25 |
-
4: 'Open'
|
26 |
-
}
|
27 |
-
|
28 |
-
origins = ["*"]
|
29 |
-
|
30 |
-
app = FastAPI()
|
31 |
-
|
32 |
-
app.add_middleware(
|
33 |
-
CORSMiddleware,
|
34 |
-
allow_origins=origins,
|
35 |
-
allow_credentials=True,
|
36 |
-
allow_methods=["*"],
|
37 |
-
allow_headers=["*"],
|
38 |
-
)
|
39 |
-
|
40 |
-
def five2one(item):
|
41 |
-
return (item - 0) / (5 - 0)
|
42 |
-
|
43 |
-
model_List = ["gpt-4", "gpt-4-0613", "gpt-3.5-turbo-16k-0613", "gpt-3.5-long"]
|
44 |
-
|
45 |
-
def get_response(model, prompt):
|
46 |
-
url = "https://gptapi.lumaticai.com/v1/chat/completions"
|
47 |
-
body = {
|
48 |
-
"model": model,
|
49 |
-
"stream": False,
|
50 |
-
"messages": [
|
51 |
-
{"role": "assistant", "content": prompt}
|
52 |
-
]
|
53 |
-
}
|
54 |
-
|
55 |
-
try:
|
56 |
-
json_response = requests.post(url, json=body).json().get('choices', [])
|
57 |
-
print(model)
|
58 |
-
for choice in json_response:
|
59 |
-
# print(choice.get('message', {}).get('content', ''))
|
60 |
-
res = choice.get('message', {}).get('content', '')
|
61 |
-
return res
|
62 |
-
except Exception as e:
|
63 |
-
# print('Error : ', e)
|
64 |
-
return e
|
65 |
-
|
66 |
-
def get_response_with_fallback(prompt):
|
67 |
-
for model in model_List:
|
68 |
-
try:
|
69 |
-
response = get_response(model, prompt)
|
70 |
-
if not isinstance(response, Exception): # Check if it's an error
|
71 |
-
return {"response": response, "model": model}
|
72 |
-
except Exception as e:
|
73 |
-
return f"Error with model {model}: {e}"
|
74 |
-
# If none succeed, return an error message
|
75 |
-
return "Failed to generate diagnosis with any model."
|
76 |
-
|
77 |
-
@app.post("/predict", response_model=PersonalityResponse)
|
78 |
-
def predict_personality(request: PersonalityRequest):
|
79 |
-
input_datas = list(map(five2one, request.responses))
|
80 |
-
|
81 |
-
input_data = np.array(input_datas).reshape(1, -1, 1)
|
82 |
-
|
83 |
-
prediction = model.predict(input_data)
|
84 |
-
|
85 |
-
personality_type = int(np.argmax(prediction, axis=1)[0])
|
86 |
-
personality_name = personality_mapping[personality_type]
|
87 |
-
|
88 |
-
return PersonalityResponse(personality_type=personality_type, personality_name=personality_name)
|
89 |
-
|
90 |
-
@app.post('/personality/description')
|
91 |
-
def personality_description(personality_name : str):
|
92 |
-
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: "
|
93 |
-
|
94 |
-
try:
|
95 |
-
resultt = get_response_with_fallback(prompt)
|
96 |
-
|
97 |
-
modell = resultt.get('model')
|
98 |
-
|
99 |
-
resultsj = resultt.get('response')
|
100 |
-
|
101 |
-
results = str(resultsj)
|
102 |
-
|
103 |
-
# rst = resultt.response
|
104 |
-
|
105 |
-
if isinstance(results, Exception):
|
106 |
-
return {"message": "Error generating diagnosis: " + results, "model": modell}
|
107 |
-
|
108 |
-
for line in results.split('\n'):
|
109 |
-
if line.startswith('"**Personality description:'):
|
110 |
-
ps = line.split(':**')[1].strip()
|
111 |
-
elif line.startswith('**Personality description:'):
|
112 |
-
ps = line.split(':**')[1].strip()
|
113 |
-
elif line.startswith('Personality description:'):
|
114 |
-
ps = line.split(':')[1].strip()
|
115 |
-
|
116 |
-
return ps
|
117 |
-
|
118 |
-
except Exception as e:
|
119 |
-
return {"message": "couldn't get description for " + personality_name}
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
if __name__ == "__main__":
|
124 |
-
import uvicorn
|
125 |
-
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
1 |
+
import tensorflow as tf
|
2 |
+
from tensorflow.keras.models import load_model
|
3 |
+
from pydantic import BaseModel
|
4 |
+
from typing import List
|
5 |
+
from fastapi import FastAPI
|
6 |
+
import numpy as np
|
7 |
+
import requests
|
8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
9 |
+
|
10 |
+
|
11 |
+
model = load_model('./models\\big5_gru.h5')
|
12 |
+
|
13 |
+
class PersonalityRequest(BaseModel):
|
14 |
+
responses: List[float]
|
15 |
+
|
16 |
+
class PersonalityResponse(BaseModel):
|
17 |
+
personality_type: int
|
18 |
+
personality_name: str
|
19 |
+
|
20 |
+
personality_mapping = {
|
21 |
+
0: 'Extroverted',
|
22 |
+
1: 'Neurotic',
|
23 |
+
2: 'Agreeable',
|
24 |
+
3: 'Conscientious',
|
25 |
+
4: 'Open'
|
26 |
+
}
|
27 |
+
|
28 |
+
origins = ["*"]
|
29 |
+
|
30 |
+
app = FastAPI()
|
31 |
+
|
32 |
+
app.add_middleware(
|
33 |
+
CORSMiddleware,
|
34 |
+
allow_origins=origins,
|
35 |
+
allow_credentials=True,
|
36 |
+
allow_methods=["*"],
|
37 |
+
allow_headers=["*"],
|
38 |
+
)
|
39 |
+
|
40 |
+
def five2one(item):
|
41 |
+
return (item - 0) / (5 - 0)
|
42 |
+
|
43 |
+
model_List = ["gpt-4", "gpt-4-0613", "gpt-3.5-turbo-16k-0613", "gpt-3.5-long"]
|
44 |
+
|
45 |
+
def get_response(model, prompt):
|
46 |
+
url = "https://gptapi.lumaticai.com/v1/chat/completions"
|
47 |
+
body = {
|
48 |
+
"model": model,
|
49 |
+
"stream": False,
|
50 |
+
"messages": [
|
51 |
+
{"role": "assistant", "content": prompt}
|
52 |
+
]
|
53 |
+
}
|
54 |
+
|
55 |
+
try:
|
56 |
+
json_response = requests.post(url, json=body).json().get('choices', [])
|
57 |
+
print(model)
|
58 |
+
for choice in json_response:
|
59 |
+
# print(choice.get('message', {}).get('content', ''))
|
60 |
+
res = choice.get('message', {}).get('content', '')
|
61 |
+
return res
|
62 |
+
except Exception as e:
|
63 |
+
# print('Error : ', e)
|
64 |
+
return e
|
65 |
+
|
66 |
+
def get_response_with_fallback(prompt):
|
67 |
+
for model in model_List:
|
68 |
+
try:
|
69 |
+
response = get_response(model, prompt)
|
70 |
+
if not isinstance(response, Exception): # Check if it's an error
|
71 |
+
return {"response": response, "model": model}
|
72 |
+
except Exception as e:
|
73 |
+
return f"Error with model {model}: {e}"
|
74 |
+
# If none succeed, return an error message
|
75 |
+
return "Failed to generate diagnosis with any model."
|
76 |
+
|
77 |
+
@app.post("/predict", response_model=PersonalityResponse)
|
78 |
+
def predict_personality(request: PersonalityRequest):
|
79 |
+
input_datas = list(map(five2one, request.responses))
|
80 |
+
|
81 |
+
input_data = np.array(input_datas).reshape(1, -1, 1)
|
82 |
+
|
83 |
+
prediction = model.predict(input_data)
|
84 |
+
|
85 |
+
personality_type = int(np.argmax(prediction, axis=1)[0])
|
86 |
+
personality_name = personality_mapping[personality_type]
|
87 |
+
|
88 |
+
return PersonalityResponse(personality_type=personality_type, personality_name=personality_name)
|
89 |
+
|
90 |
+
@app.post('/personality/description')
|
91 |
+
def personality_description(personality_name : str):
|
92 |
+
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: "
|
93 |
+
|
94 |
+
try:
|
95 |
+
resultt = get_response_with_fallback(prompt)
|
96 |
+
|
97 |
+
modell = resultt.get('model')
|
98 |
+
|
99 |
+
resultsj = resultt.get('response')
|
100 |
+
|
101 |
+
results = str(resultsj)
|
102 |
+
|
103 |
+
# rst = resultt.response
|
104 |
+
|
105 |
+
if isinstance(results, Exception):
|
106 |
+
return {"message": "Error generating diagnosis: " + results, "model": modell}
|
107 |
+
|
108 |
+
for line in results.split('\n'):
|
109 |
+
if line.startswith('"**Personality description:'):
|
110 |
+
ps = line.split(':**')[1].strip()
|
111 |
+
elif line.startswith('**Personality description:'):
|
112 |
+
ps = line.split(':**')[1].strip()
|
113 |
+
elif line.startswith('Personality description:'):
|
114 |
+
ps = line.split(':')[1].strip()
|
115 |
+
|
116 |
+
return ps
|
117 |
+
|
118 |
+
except Exception as e:
|
119 |
+
return {"message": "couldn't get description for " + personality_name}
|
120 |
+
|
121 |
+
|
122 |
+
|
123 |
+
if __name__ == "__main__":
|
124 |
+
import uvicorn
|
125 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|