Chompi10 commited on
Commit
3c2f1c9
verified
1 Parent(s): 6929287

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -152
app.py CHANGED
@@ -3,13 +3,19 @@ import torch
3
  from flask import Flask, request, jsonify, Response
4
  from transformers import AutoTokenizer, AutoModelForCausalLM
5
 
 
 
 
 
6
  app = Flask(__name__)
7
 
8
  MODEL_NAME = "microsoft/phi-2"
9
- MAX_NEW_TOKENS = 400
10
 
11
  print("Cargando modelo...")
12
 
 
 
13
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
14
 
15
  model = AutoModelForCausalLM.from_pretrained(
@@ -24,8 +30,75 @@ print("Modelo cargado correctamente.")
24
 
25
 
26
  # ===============================
27
- # FRONTEND
28
  # ===============================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  @app.route("/")
30
  def index():
31
  return Response("""
@@ -33,70 +106,20 @@ def index():
33
  <html>
34
  <head>
35
  <meta charset="UTF-8">
36
- <title>AI Assistant</title>
37
  <style>
38
- body {
39
- margin:0;
40
- font-family:Arial;
41
- background:#343541;
42
- display:flex;
43
- justify-content:center;
44
- align-items:center;
45
- height:100vh;
46
- }
47
- .container{
48
- width:800px;
49
- height:90vh;
50
- background:#444654;
51
- display:flex;
52
- flex-direction:column;
53
- border-radius:10px;
54
- }
55
- .chat{
56
- flex:1;
57
- padding:20px;
58
- overflow-y:auto;
59
- display:flex;
60
- flex-direction:column;
61
- }
62
- .msg{
63
- padding:12px;
64
- border-radius:8px;
65
- margin-bottom:12px;
66
- max-width:85%;
67
- white-space:pre-wrap;
68
- }
69
- .user{
70
- background:#19c37d;
71
- align-self:flex-end;
72
- color:black;
73
- }
74
- .bot{
75
- background:#555869;
76
- align-self:flex-start;
77
- color:white;
78
- }
79
- .input-area{
80
- display:flex;
81
- border-top:1px solid #555;
82
- }
83
- input{
84
- flex:1;
85
- padding:15px;
86
- border:none;
87
- outline:none;
88
- font-size:16px;
89
- }
90
- button{
91
- padding:15px;
92
- border:none;
93
- background:#19c37d;
94
- font-weight:bold;
95
- cursor:pointer;
96
- }
97
- button:hover{
98
- opacity:0.9;
99
- }
100
  </style>
101
  </head>
102
  <body>
@@ -104,6 +127,11 @@ button:hover{
104
  <div class="container">
105
  <div id="chat" class="chat"></div>
106
  <div class="input-area">
 
 
 
 
 
107
  <input id="input" placeholder="Write your message..." />
108
  <button onclick="send()">Send</button>
109
  </div>
@@ -113,6 +141,7 @@ button:hover{
113
  async function send(){
114
  const input = document.getElementById("input");
115
  const chat = document.getElementById("chat");
 
116
 
117
  const text = input.value.trim();
118
  if(!text) return;
@@ -126,7 +155,7 @@ async function send(){
126
  const res = await fetch("/chat",{
127
  method:"POST",
128
  headers:{"Content-Type":"application/json"},
129
- body:JSON.stringify({message:text})
130
  });
131
 
132
  const data = await res.json();
@@ -162,97 +191,24 @@ document.getElementById("input").addEventListener("keypress",function(e){
162
  # ===============================
163
  # API CHAT
164
  # ===============================
 
165
  @app.route("/chat", methods=["POST"])
166
  def chat():
167
  try:
168
  data = request.get_json()
169
  user_input = data.get("message", "")
 
170
 
171
  if not user_input:
172
  return jsonify({"error": "Empty message"}), 400
173
 
174
- # PROMPT MULTI-LENGUAJE + C脫DIGO COMPLETO
175
- system_prompt = """
176
- GENERATOR_PROMPT = """
177
- You are a Senior Software Engineer.
178
-
179
- Generate:
180
- - Clean
181
- - Secure
182
- - Optimized
183
- - Production-ready code
184
- Explain briefly what the code does.
185
- Include best practices.
186
-
187
- """
188
-
189
- ULTRA_REVIEW_PROMPT = """
190
-
191
- You are a Principal Software Architect and Security Engineer.
192
- Perform an EXTREMELY CRITICAL and PROFESSIONAL code review.
193
- Be strict. Be precise.
194
- Analyze:
195
- 1. Logical correctness
196
- 2. Edge cases
197
- 3. Security vulnerabilities (OWASP mindset)
198
- 4. Input validation
199
- 5. Authentication flaws
200
- 6. Concurrency risks
201
- 7. Memory inefficiencies
202
- 8. Performance bottlenecks
203
- 9. Scalability risks
204
- 10. SOLID violations
205
- 11. Clean Architecture violations
206
- 12. Code smells
207
- 13. Dependency risks
208
- 14. Error handling weaknesses
209
- 15. Logging gaps
210
- 16. Deployment risks
211
-
212
- Return STRICTLY in this structure:
213
-
214
- ## Executive Summary
215
- ## Critical Bugs
216
- ## Security Vulnerabilities
217
- ## Architecture Problems
218
- ## Scalability Risks
219
- ## Performance Issues
220
- ## Code Quality Problems
221
- ## Missing Edge Cases
222
- ## Refactored Version
223
- ## Final Verdict
224
- """
225
-
226
- ARCHITECTURE_ANALYSIS_PROMPT = """
227
- You are a Senior Software Architect.
228
-
229
- Analyze the provided system from an ARCHITECTURAL perspective.
230
-
231
- Evaluate:
232
-
233
- - Layered architecture
234
- - Coupling and cohesion
235
- - Domain boundaries
236
- - API design
237
- - Data flow
238
- - Scalability model
239
- - Fault tolerance
240
- - Observability
241
- - Cloud readiness
242
- - Caching strategy
243
- - Database strategy
244
- - Horizontal scaling capability
245
-
246
- Return response in this format:
247
-
248
- ## Architecture Overview
249
- ## Structural Problems
250
- ## Scalability Evaluation
251
- ## Resilience Evaluation
252
- ## Design Improvements
253
- ## Suggested Architecture
254
- ## Final Architectural Verdict
255
- """
256
 
257
  prompt = f"{system_prompt}\nUser: {user_input}\nAssistant:"
258
 
@@ -263,10 +219,10 @@ Return response in this format:
263
  **inputs,
264
  max_new_tokens=MAX_NEW_TOKENS,
265
  do_sample=True,
266
- temperature=0.8,
267
- top_p=0.8,
268
- repetition_penalty=1.1,
269
- no_repeat_ngram_size=2,
270
  pad_token_id=tokenizer.eos_token_id
271
  )
272
 
@@ -279,6 +235,10 @@ Return response in this format:
279
  return jsonify({"error": str(e)}), 500
280
 
281
 
 
 
 
 
282
  if __name__ == "__main__":
283
  port = int(os.environ.get("PORT", 7860))
284
  app.run(host="0.0.0.0", port=port)
 
3
  from flask import Flask, request, jsonify, Response
4
  from transformers import AutoTokenizer, AutoModelForCausalLM
5
 
6
+ # ===============================
7
+ # CONFIGURACI脫N B脕SICA
8
+ # ===============================
9
+
10
  app = Flask(__name__)
11
 
12
  MODEL_NAME = "microsoft/phi-2"
13
+ MAX_NEW_TOKENS = 250
14
 
15
  print("Cargando modelo...")
16
 
17
+ torch.set_num_threads(4)
18
+
19
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
20
 
21
  model = AutoModelForCausalLM.from_pretrained(
 
30
 
31
 
32
  # ===============================
33
+ # PROMPTS PROFESIONALES
34
  # ===============================
35
+
36
+ GENERATOR_PROMPT = """
37
+ You are a Senior Software Engineer.
38
+ Always respond in the same language as the user.
39
+
40
+ Generate:
41
+ - Clean
42
+ - Secure
43
+ - Optimized
44
+ - Production-ready code
45
+ Explain briefly what the code does.
46
+ Include best practices.
47
+ Use markdown triple backticks for code blocks.
48
+ """
49
+
50
+ ULTRA_REVIEW_PROMPT = """
51
+ You are a Principal Software Architect and Security Engineer.
52
+ Always respond in the same language as the user.
53
+
54
+ Perform an EXTREMELY CRITICAL and PROFESSIONAL code review.
55
+
56
+ Analyze:
57
+ 1. Logical correctness
58
+ 2. Edge cases
59
+ 3. Security vulnerabilities (OWASP mindset)
60
+ 4. Input validation
61
+ 5. Authentication flaws
62
+ 6. Concurrency risks
63
+ 7. Memory inefficiencies
64
+ 8. Performance bottlenecks
65
+ 9. Scalability risks
66
+ 10. SOLID violations
67
+ 11. Clean Architecture violations
68
+ 12. Code smells
69
+ 13. Dependency risks
70
+ 14. Error handling weaknesses
71
+ 15. Logging gaps
72
+ 16. Deployment risks
73
+
74
+ Return structured sections with clear headings.
75
+ """
76
+
77
+ ARCHITECTURE_ANALYSIS_PROMPT = """
78
+ You are a Senior Software Architect.
79
+ Always respond in the same language as the user.
80
+
81
+ Analyze the provided system from an ARCHITECTURAL perspective.
82
+
83
+ Evaluate:
84
+ - Layered architecture
85
+ - Coupling and cohesion
86
+ - API design
87
+ - Data flow
88
+ - Scalability model
89
+ - Fault tolerance
90
+ - Cloud readiness
91
+ - Observability
92
+ - Caching strategy
93
+
94
+ Return structured response with headings.
95
+ """
96
+
97
+
98
+ # ===============================
99
+ # FRONTEND (CHAT UI)
100
+ # ===============================
101
+
102
  @app.route("/")
103
  def index():
104
  return Response("""
 
106
  <html>
107
  <head>
108
  <meta charset="UTF-8">
109
+ <title>AI Engineer Assistant</title>
110
  <style>
111
+ body { margin:0; font-family:Arial; background:#343541; display:flex; justify-content:center; align-items:center; height:100vh; }
112
+ .container { width:900px; height:92vh; background:#444654; display:flex; flex-direction:column; border-radius:10px; }
113
+ .chat { flex:1; padding:20px; overflow-y:auto; display:flex; flex-direction:column; }
114
+ .msg { padding:12px; border-radius:8px; margin-bottom:12px; max-width:85%; white-space:pre-wrap; }
115
+ .user { background:#19c37d; align-self:flex-end; color:black; }
116
+ .bot { background:#555869; align-self:flex-start; color:white; }
117
+ .input-area { display:flex; border-top:1px solid #555; }
118
+ input, select { padding:15px; border:none; outline:none; font-size:16px; }
119
+ input { flex:1; }
120
+ button { padding:15px; border:none; background:#19c37d; font-weight:bold; cursor:pointer; }
121
+ button:hover { opacity:0.9; }
122
+ select { background:#555869; color:white; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  </style>
124
  </head>
125
  <body>
 
127
  <div class="container">
128
  <div id="chat" class="chat"></div>
129
  <div class="input-area">
130
+ <select id="mode">
131
+ <option value="generate">Generate Code</option>
132
+ <option value="review">Ultra Review</option>
133
+ <option value="architecture">Architecture Analysis</option>
134
+ </select>
135
  <input id="input" placeholder="Write your message..." />
136
  <button onclick="send()">Send</button>
137
  </div>
 
141
  async function send(){
142
  const input = document.getElementById("input");
143
  const chat = document.getElementById("chat");
144
+ const mode = document.getElementById("mode").value;
145
 
146
  const text = input.value.trim();
147
  if(!text) return;
 
155
  const res = await fetch("/chat",{
156
  method:"POST",
157
  headers:{"Content-Type":"application/json"},
158
+ body:JSON.stringify({message:text, mode:mode})
159
  });
160
 
161
  const data = await res.json();
 
191
  # ===============================
192
  # API CHAT
193
  # ===============================
194
+
195
  @app.route("/chat", methods=["POST"])
196
  def chat():
197
  try:
198
  data = request.get_json()
199
  user_input = data.get("message", "")
200
+ mode = data.get("mode", "generate")
201
 
202
  if not user_input:
203
  return jsonify({"error": "Empty message"}), 400
204
 
205
+ # Selecci贸n de prompt seg煤n modo
206
+ if mode == "review":
207
+ system_prompt = ULTRA_REVIEW_PROMPT
208
+ elif mode == "architecture":
209
+ system_prompt = ARCHITECTURE_ANALYSIS_PROMPT
210
+ else:
211
+ system_prompt = GENERATOR_PROMPT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
  prompt = f"{system_prompt}\nUser: {user_input}\nAssistant:"
214
 
 
219
  **inputs,
220
  max_new_tokens=MAX_NEW_TOKENS,
221
  do_sample=True,
222
+ temperature=0.5,
223
+ top_p=0.9,
224
+ repetition_penalty=1.15,
225
+ no_repeat_ngram_size=3,
226
  pad_token_id=tokenizer.eos_token_id
227
  )
228
 
 
235
  return jsonify({"error": str(e)}), 500
236
 
237
 
238
+ # ===============================
239
+ # START SERVER
240
+ # ===============================
241
+
242
  if __name__ == "__main__":
243
  port = int(os.environ.get("PORT", 7860))
244
  app.run(host="0.0.0.0", port=port)