hfariborzi commited on
Commit
5e5dfdc
·
verified ·
1 Parent(s): 458ede3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -0
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from dotenv import load_dotenv
4
+ from fastapi import FastAPI, HTTPException
5
+ from pydantic import BaseModel
6
+ import openai
7
+ import numpy as np
8
+ import pandas as pd
9
+ from sklearn.linear_model import LinearRegression
10
+ import requests
11
+
12
+ # Load environment variables from the .env file
13
+ load_dotenv()
14
+
15
+ # Set the OpenAI API key
16
+ openai.api_key = os.getenv("OPENAI_API_KEY")
17
+
18
+ # File paths
19
+ predefined_constructs_file = "/app/predefined_constructs.txt"
20
+ full_matrix_path = "/app/no_na_matrix.csv"
21
+
22
+ # Logging configuration
23
+ logging.basicConfig(
24
+ level=logging.DEBUG,
25
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
26
+ handlers=[
27
+ logging.FileHandler("app.log"),
28
+ logging.StreamHandler()
29
+ ]
30
+ )
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ # FastAPI application
35
+ app = FastAPI()
36
+
37
+ # Request schema
38
+ class InferenceRequest(BaseModel):
39
+ query: str
40
+
41
+ # Functions for inference
42
+ def read_predefined_constructs(file_path):
43
+ with open(file_path, 'r') as file:
44
+ return file.read()
45
+
46
+ def call_openai_chat(model, messages):
47
+ url = "https://api.openai.com/v1/chat/completions"
48
+ headers = {
49
+ "Content-Type": "application/json",
50
+ "Authorization": f"Bearer {openai.api_key}",
51
+ }
52
+ data = {"model": model, "messages": messages}
53
+ response = requests.post(url, headers=headers, json=data)
54
+ response.raise_for_status()
55
+ return response.json()["choices"][0]["message"]["content"]
56
+
57
+ def clean_predefined_constructs_and_matrix(predefined_constructs_path, full_matrix_path):
58
+ with open(predefined_constructs_path, "r") as f:
59
+ predefined_constructs = [
60
+ line.split('\t')[0].strip().lower()
61
+ for line in f.readlines() if line.strip()
62
+ ]
63
+
64
+ predefined_constructs = [
65
+ c.replace('-', ' ').replace('–', ' ').replace('(', '')
66
+ .replace(')', '').replace('/', ' ').replace(',', ' ')
67
+ .replace('.', ' ').strip()
68
+ for c in predefined_constructs if c != "variable"
69
+ ]
70
+
71
+ full_matrix = pd.read_csv(full_matrix_path, index_col=0)
72
+ full_matrix.index = full_matrix.index.str.strip().str.lower().str.replace('[^a-z0-9 ]', '', regex=True)
73
+ full_matrix.columns = full_matrix.columns.str.strip().str.lower().str.replace('[^a-z0-9 ]', '', regex=True)
74
+
75
+ valid_constructs = set(predefined_constructs)
76
+ matrix_rows = set(full_matrix.index)
77
+ matrix_columns = set(full_matrix.columns)
78
+
79
+ invalid_rows = matrix_rows - valid_constructs
80
+ invalid_columns = matrix_columns - valid_constructs
81
+
82
+ full_matrix = full_matrix.drop(index=invalid_rows, errors='ignore')
83
+ full_matrix = full_matrix.drop(columns=invalid_columns, errors='ignore')
84
+
85
+ missing_constructs = [c for c in predefined_constructs if c not in full_matrix.index or c not in full_matrix.columns]
86
+ if missing_constructs:
87
+ raise ValueError(f"Missing constructs in the correlation matrix: {missing_constructs}")
88
+
89
+ return predefined_constructs, full_matrix
90
+
91
+ def construct_analyzer(user_prompt, predefined_constructs):
92
+ predefined_constructs_prompt = "\n".join(predefined_constructs)
93
+ prompt_text = (
94
+ f"Here is the user's prompt: '{user_prompt}'.\n\n"
95
+ "Your role is to identify 10 relevant constructs from the provided list. "
96
+ "Pick one variable as the dependent variable. Format output as:\n"
97
+ "var1|var2|...|var10;dependent_var\n\n"
98
+ f"{predefined_constructs_prompt}"
99
+ )
100
+
101
+ messages = [
102
+ {"role": "system", "content": "You are a construct analyzer."},
103
+ {"role": "user", "content": prompt_text},
104
+ ]
105
+ constructs_with_dependent = call_openai_chat(model="gpt-4", messages=messages).strip()
106
+ constructs_list, dependent_variable = constructs_with_dependent.split(';')
107
+ constructs = constructs_list.split('|')
108
+
109
+ if dependent_variable not in constructs:
110
+ constructs.append(dependent_variable)
111
+
112
+ return constructs, dependent_variable
113
+
114
+ def regression_analyst(correlation_matrix, dependent_variable):
115
+ normalized_dependent = dependent_variable.strip().lower()
116
+ normalized_columns = [col.strip().lower() for col in correlation_matrix.columns]
117
+
118
+ if normalized_dependent not in normalized_columns:
119
+ from difflib import get_close_matches
120
+ suggestions = get_close_matches(normalized_dependent, normalized_columns, n=3, cutoff=0.6)
121
+ raise KeyError(
122
+ f"Dependent variable '{dependent_variable}' not found. Suggestions: {suggestions}"
123
+ )
124
+
125
+ original_dependent = correlation_matrix.columns[normalized_columns.index(normalized_dependent)]
126
+ independent_vars = [var for var in correlation_matrix.columns if var != original_dependent]
127
+
128
+ synthetic_data = np.random.multivariate_normal(
129
+ mean=np.zeros(len(correlation_matrix)),
130
+ cov=correlation_matrix.to_numpy(),
131
+ size=1000
132
+ )
133
+ synthetic_data = pd.DataFrame(synthetic_data, columns=correlation_matrix.columns)
134
+ X = synthetic_data[independent_vars]
135
+ y = synthetic_data[original_dependent]
136
+
137
+ model = LinearRegression()
138
+ model.fit(X, y)
139
+ beta_weights = model.coef_
140
+
141
+ return independent_vars, beta_weights
142
+
143
+ def generate_inference(user_query, equation, independent_vars, dependent_variable, beta_weights):
144
+ beta_details = "\n".join([f"{var}: {round(beta, 4)}" for var, beta in zip(independent_vars, beta_weights)])
145
+ prompt = (
146
+ f"User query: '{user_query}'\n"
147
+ f"Regression Equation: {equation}\n"
148
+ f"Variables and Beta Weights:\n{beta_details}\n\n"
149
+ "Provide actionable insights based on this analysis."
150
+ )
151
+
152
+ messages = [
153
+ {"role": "system", "content": "You are a skilled analyst interpreting regression results."},
154
+ {"role": "user", "content": prompt},
155
+ ]
156
+ return call_openai_chat(model="gpt-4", messages=messages).strip()
157
+
158
+ def run_inference_pipeline(user_query, predefined_constructs, correlation_matrix):
159
+ constructs_raw, dependent_variable = construct_analyzer(user_query, predefined_constructs)
160
+ constructs_list = constructs_raw.split('|')
161
+
162
+ if dependent_variable not in constructs_list:
163
+ constructs_list.append(dependent_variable)
164
+
165
+ correlation_matrix_filtered = correlation_matrix.loc[constructs_list, constructs_list]
166
+ independent_vars, beta_weights = regression_analyst(correlation_matrix_filtered, dependent_variable)
167
+
168
+ equation = f"{dependent_variable} = " + " + ".join(
169
+ [f"{round(beta, 4)}*{var}" for beta, var in zip(beta_weights, independent_vars)]
170
+ )
171
+
172
+ inference = generate_inference(user_query, equation, independent_vars, dependent_variable, beta_weights)
173
+
174
+ return {"equation": equation, "inference": inference}
175
+
176
+ # API endpoint
177
+ @app.post("/infer")
178
+ def infer(request: InferenceRequest):
179
+ try:
180
+ predefined_constructs, cleaned_matrix = clean_predefined_constructs_and_matrix(predefined_constructs_file, full_matrix_path)
181
+ results = run_inference_pipeline(request.query, predefined_constructs, cleaned_matrix)
182
+ return results
183
+ except Exception as e:
184
+ logger.error(f"Error during inference: {e}")
185
+ raise HTTPException(status_code=500, detail=str(e))