CosmickVisions commited on
Commit
91c951d
·
verified ·
1 Parent(s): cd5be39

Update app_backend.py

Browse files
Files changed (1) hide show
  1. app_backend.py +48 -64
app_backend.py CHANGED
@@ -1,87 +1,71 @@
1
  from flask import Flask, request, jsonify
2
  from flask_cors import CORS
3
- import os
4
  import openai
5
- import pandas as pd
6
  import json
7
- from functools import lru_cache
8
 
9
  app = Flask(__name__)
10
- CORS(app) # Enable CORS for cross-origin requests
11
 
12
  # Configure DeepSeek API
13
  openai.api_key = os.getenv("DEEPSEEK_API_KEY")
14
  openai.api_base = "https://api.deepseek.com/v1"
15
 
16
- # Cache for expensive computations (e.g., dataset stats)
17
- @lru_cache(maxsize=128)
18
- def get_dataset_stats(df_json):
19
- df = pd.read_json(df_json)
20
- stats = {
21
- "rows": df.shape[0],
22
- "columns": df.shape[1],
23
- "missing_values": df.isna().sum().sum(),
24
- "column_types": {col: str(df[col].dtype) for col in df.columns},
25
- }
26
- return stats
27
-
28
- @app.route('/chat', methods=['POST'])
29
- def chat():
30
- try:
31
- data = request.json
32
- user_input = data.get('message')
33
- df_json = data.get('dataset', None)
34
- problem_type = data.get('problem_type', None)
35
- target = data.get('target', None)
36
- best_model = data.get('best_model', None)
37
 
38
- # Get dataset stats if available
39
- context = ""
40
- if df_json:
41
- stats = get_dataset_stats(df_json)
42
- context += f"Dataset Stats:\n- Rows: {stats['rows']}\n- Columns: {stats['columns']}\n- Missing Values: {stats['missing_values']}\n"
43
- context += "Column Types:\n"
44
- for col, dtype in stats['column_types'].items():
45
- context += f"- {col}: {dtype}\n"
46
 
47
- if problem_type:
48
- context += f"Problem Type: {problem_type}\n"
49
- if target:
50
- context += f"Target Column: {target}\n"
51
- if best_model:
52
- context += f"Best Model: {best_model}\n"
53
-
54
- # Create enhanced prompt with context
55
- system_prompt = (
56
- "You are an AI assistant in Neural-Vision Enhanced, a data analysis and modeling app. "
57
- "The app has three pages:\n"
58
- "- **Data Upload**: Upload CSV files, view stats, or generate EDA reports.\n"
59
- "- **Model Training**: Train classification, regression, or clustering models using PyCaret.\n"
60
- "- **Validation & Exploration**: Evaluate and visualize trained models.\n"
61
- f"Current context:\n{context}"
62
- )
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  # Call DeepSeek API
65
  response = openai.ChatCompletion.create(
66
  model="deepseek-chat",
67
- messages=[
68
- {"role": "system", "content": system_prompt},
69
- {"role": "user", "content": user_input}
70
- ],
71
- temperature=0.7,
 
 
 
72
  max_tokens=500
73
  )
74
-
75
- return jsonify({
76
- "response": response.choices[0].message.content,
77
- "status": "success"
78
- })
79
-
80
  except Exception as e:
81
- return jsonify({
82
- "response": f"Error: {str(e)}",
83
- "status": "error"
84
- }), 500
85
 
86
  if __name__ == '__main__':
87
  app.run(host='0.0.0.0', port=5001)
 
1
  from flask import Flask, request, jsonify
2
  from flask_cors import CORS
 
3
  import openai
4
+ import os
5
  import json
 
6
 
7
  app = Flask(__name__)
8
+ CORS(app)
9
 
10
  # Configure DeepSeek API
11
  openai.api_key = os.getenv("DEEPSEEK_API_KEY")
12
  openai.api_base = "https://api.deepseek.com/v1"
13
 
14
+ # System prompt for the AI assistant
15
+ SYSTEM_PROMPT = '''
16
+ You are Neural Analyst, an AI assistant for the Neural-Vision Enhanced analytics platform.
17
+ Your capabilities include:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ 1. Explaining model metrics and evaluation visualizations
20
+ 2. Interpreting dataset statistics and EDA reports
21
+ 3. Guiding users through app functionality
22
+ 4. Providing data science insights
23
+ 5. Comparing different model performances
 
 
 
24
 
25
+ Always consider:
26
+ - Current dataset statistics: {dataset_stats}
27
+ - Active problem type: {problem_type}
28
+ - Model metrics: {metrics}
29
+ - App state: {active_page}
30
+ '''
 
 
 
 
 
 
 
 
 
 
31
 
32
+ @app.route('/analyze', methods=['POST'])
33
+ def analyze():
34
+ try:
35
+ data = request.json
36
+ context = json.loads(data['context'])
37
+
38
+ # Construct the prompt for DeepSeek
39
+ prompt = f'''
40
+ User Query: {data['prompt']}
41
+
42
+ Current Context:
43
+ - Active Page: {context['current_state']['active_page']}
44
+ - Problem Type: {context['current_state']['problem_type']}
45
+ - Target Variable: {context['current_state']['target']}
46
+ - Dataset Shape: {context['current_state']['dataset_stats'].get('rows', 0)} rows,
47
+ {context['current_state']['dataset_stats'].get('columns', 0)} columns
48
+ - Model Metrics: {json.dumps(context['current_state']['model_metrics'])}
49
+ '''
50
+
51
  # Call DeepSeek API
52
  response = openai.ChatCompletion.create(
53
  model="deepseek-chat",
54
+ messages=[{
55
+ "role": "system",
56
+ "content": SYSTEM_PROMPT.format(**context['current_state'])
57
+ }, {
58
+ "role": "user",
59
+ "content": prompt
60
+ }],
61
+ temperature=0.3,
62
  max_tokens=500
63
  )
64
+
65
+ return jsonify({"analysis": response.choices[0].message.content})
66
+
 
 
 
67
  except Exception as e:
68
+ return jsonify({"error": str(e)}), 500
 
 
 
69
 
70
  if __name__ == '__main__':
71
  app.run(host='0.0.0.0', port=5001)