Rudert commited on
Commit
12449aa
·
verified ·
1 Parent(s): cd04fd7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +317 -0
app.py CHANGED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, send_from_directory
2
+ from openai import OpenAI
3
+ import os
4
+ import json
5
+ import sqlite3
6
+ from dotenv import load_dotenv
7
+ import time
8
+
9
+ # Load environment variables
10
+ load_dotenv()
11
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
12
+
13
+ if not GROQ_API_KEY:
14
+ raise ValueError("GROQ_API_KEY tidak ditemukan di .env")
15
+
16
+ # Initialize Flask app
17
+ app = Flask(__name__)
18
+
19
+ # Initialize OpenAI client
20
+ client = OpenAI(
21
+ base_url="https://api.groq.com/openai/v1",
22
+ api_key=GROQ_API_KEY
23
+ )
24
+
25
+ # Database initialization (gunakan SQLite atau pustaka lainnya)
26
+ # Misalnya, untuk menyimpan riwayat percakapan
27
+ conn = sqlite3.connect('chat_history.db', check_same_thread=False)
28
+ c = conn.cursor()
29
+ c.execute('''CREATE TABLE IF NOT EXISTS chat_history
30
+ (id INTEGER PRIMARY KEY AUTOINCREMENT,
31
+ conversation_id INTEGER,
32
+ role TEXT,
33
+ content TEXT,
34
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
35
+ conn.commit()
36
+
37
+ # Language Knowledge Base (ambil dari kode asli)
38
+ LANGUAGE_KNOWLEDGE = {
39
+ "python": {
40
+ "frameworks": ["Django", "Flask", "FastAPI", "Streamlit", "PyQt", "Tkinter"],
41
+ "paradigms": ["OOP", "Functional", "Procedural", "Imperative"],
42
+ "extension": ".py",
43
+ "hello_world": "print('Hello, World!')",
44
+ "package_manager": "pip",
45
+ "runtime": "CPython, PyPy, Jython",
46
+ "typing": "Dynamic, Optional Static (Type hints)",
47
+ "use_cases": ["Web Development", "Data Science", "AI/ML", "Automation", "Scripting"],
48
+ "special_notes": "Interpreted language with extensive libraries. Great for beginners and rapid prototyping."
49
+ },
50
+ "javascript": {
51
+ "frameworks": ["React", "Vue", "Angular", "Node.js", "Express", "Next.js", "Svelte"],
52
+ "paradigms": ["OOP", "Functional", "Event-driven", "Prototype-based"],
53
+ "extension": ".js",
54
+ "hello_world": "console.log('Hello, World!');",
55
+ "package_manager": "npm/yarn",
56
+ "runtime": "Node.js, Browser V8",
57
+ "typing": "Dynamic, Optional Static (TypeScript)",
58
+ "use_cases": ["Web Frontend", "Backend", "Mobile Apps", "Desktop Apps"],
59
+ "special_notes": "The language of the web. Runs everywhere from browsers to servers."
60
+ },
61
+ "typescript": {
62
+ "frameworks": ["Angular", "React", "Vue", "NestJS"],
63
+ "paradigms": ["OOP", "Functional", "Event-driven"],
64
+ "extension": ".ts",
65
+ "hello_world": "console.log('Hello, World!');",
66
+ "package_manager": "npm/yarn",
67
+ "runtime": "Node.js, Browser (compiled to JS)",
68
+ "typing": "Static, Strong",
69
+ "use_cases": ["Large-scale Web Apps", "Enterprise Applications"],
70
+ "special_notes": "JavaScript with static typing. Catches errors at compile time."
71
+ },
72
+ "java": {
73
+ "frameworks": ["Spring", "Hibernate", "Jakarta EE", "Quarkus", "Micronaut"],
74
+ "paradigms": ["OOP", "Concurrent", "Imperative"],
75
+ "extension": ".java",
76
+ "hello_world": 'public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } }',
77
+ "package_manager": "Maven/Gradle",
78
+ "runtime": "JVM (Java Virtual Machine)",
79
+ "typing": "Static, Strong",
80
+ "use_cases": ["Enterprise Applications", "Android Apps", "Big Data", "Banking Systems"],
81
+ "special_notes": "Write once, run anywhere. Strong emphasis on OOP and platform independence."
82
+ },
83
+ "lua": {
84
+ "frameworks": ["LÖVE", "Corona SDK", "MOAI"],
85
+ "paradigms": ["Procedural", "OOP", "Functional", "Data-driven"],
86
+ "extension": ".lua",
87
+ "hello_world": "print('Hello, World!')",
88
+ "package_manager": "LuaRocks",
89
+ "runtime": "Lua VM",
90
+ "typing": "Dynamic, Weak",
91
+ "use_cases": ["Game Development", "Embedded Systems", "Scripting", "Configuration"],
92
+ "special_notes": "Lightweight, embeddable scripting language. Often used in games and applications."
93
+ },
94
+ "luau": {
95
+ "frameworks": ["Roblox Studio"],
96
+ "paradigms": ["OOP", "Procedural", "Data-driven"],
97
+ "extension": ".lua",
98
+ "hello_world": "print('Hello, World!')",
99
+ "package_manager": "Roblox Studio",
100
+ "runtime": "Roblox Engine",
101
+ "typing": "Dynamic with optional type annotations",
102
+ "use_cases": ["Roblox Game Development", "Game Scripting"],
103
+ "special_notes": "Luau is a scripting language derived from Lua 5.1, used primarily for Roblox game development. Has gradual typing and performance optimizations."
104
+ },
105
+ "html": {
106
+ "frameworks": ["Bootstrap", "Tailwind CSS", "Foundation"],
107
+ "paradigms": ["Markup", "Declarative"],
108
+ "extension": ".html",
109
+ "hello_world": "<!DOCTYPE html><html><head><title>Hello</title></head><body><h1>Hello, World!</h1></body></html>",
110
+ "package_manager": "None",
111
+ "runtime": "Web Browser",
112
+ "typing": "None",
113
+ "use_cases": ["Web Pages", "Web Applications", "Email Templates"],
114
+ "special_notes": "Markup language for creating web pages. Not a programming language."
115
+ },
116
+ "css": {
117
+ "frameworks": ["Bootstrap", "Tailwind CSS", "Sass", "Less"],
118
+ "paradigms": ["Styling", "Declarative"],
119
+ "extension": ".css",
120
+ "hello_world": "body { color: blue; font-family: Arial; }",
121
+ "package_manager": "npm (for preprocessors)",
122
+ "runtime": "Web Browser",
123
+ "typing": "None",
124
+ "use_cases": ["Web Styling", "Responsive Design", "Animations"],
125
+ "special_notes": "Style sheet language for describing presentation of documents."
126
+ },
127
+ "cpp": {
128
+ "frameworks": ["Qt", "Boost", "STL", "Unreal Engine"],
129
+ "paradigms": ["OOP", "Procedural", "Generic", "Functional"],
130
+ "extension": ".cpp",
131
+ "hello_world": """#include <iostream>
132
+ int main() { std::cout << "Hello, World!"; return 0; }""",
133
+ "package_manager": "vcpkg/conan",
134
+ "runtime": "Native Compilation",
135
+ "typing": "Static, Strong",
136
+ "use_cases": ["System Programming", "Game Development", "High-Performance Computing", "Embedded Systems"],
137
+ "special_notes": "Extension of C with OOP features. High performance, manual memory management."
138
+ },
139
+ "rust": {
140
+ "frameworks": ["Actix", "Rocket", "Tokio"],
141
+ "paradigms": ["Multi-paradigm", "Functional", "Concurrent"],
142
+ "extension": ".rs",
143
+ "hello_world": """fn main() { println!("Hello, World!"); }""",
144
+ "package_manager": "Cargo",
145
+ "runtime": "Native Compilation",
146
+ "typing": "Static, Strong",
147
+ "use_cases": ["System Programming", "Web Assembly", "CLI Tools", "Networking"],
148
+ "special_notes": "Memory safety without garbage collection. Zero-cost abstractions."
149
+ },
150
+ "go": {
151
+ "frameworks": ["Gin", "Echo", "Fiber"],
152
+ "paradigms": ["Concurrent", "Procedural", "Imperative"],
153
+ "extension": ".go",
154
+ "hello_world": """package main
155
+ import "fmt"
156
+ func main() { fmt.Println("Hello, World!") }""",
157
+ "package_manager": "Go Modules",
158
+ "runtime": "Native Compilation",
159
+ "typing": "Static, Strong",
160
+ "use_cases": ["Backend Services", "CLI Tools", "Networking", "Cloud Native"],
161
+ "special_notes": "Simple syntax, built-in concurrency, fast compilation."
162
+ },
163
+ "php": {
164
+ "frameworks": ["Laravel", "Symfony", "CodeIgniter"],
165
+ "paradigms": ["OOP", "Procedural", "Functional"],
166
+ "extension": ".php",
167
+ "hello_world": "<?php echo 'Hello, World!'; ?>",
168
+ "package_manager": "Composer",
169
+ "runtime": "Zend Engine",
170
+ "typing": "Dynamic, Optional Static",
171
+ "use_cases": ["Web Development", "WordPress", "E-commerce"],
172
+ "special_notes": "Server-side scripting language designed for web development."
173
+ },
174
+ "ruby": {
175
+ "frameworks": ["Ruby on Rails", "Sinatra", "Hanami"],
176
+ "paradigms": ["OOP", "Functional", "Metaprogramming"],
177
+ "extension": ".rb",
178
+ "hello_world": "puts 'Hello, World!'",
179
+ "package_manager": "RubyGems",
180
+ "runtime": "MRI, JRuby",
181
+ "typing": "Dynamic, Duck Typing",
182
+ "use_cases": ["Web Development", "Scripting", "DevOps"],
183
+ "special_notes": "Developer happiness focus. 'Everything is an object' philosophy."
184
+ },
185
+ "swift": {
186
+ "frameworks": ["SwiftUI", "UIKit", "Vapor"],
187
+ "paradigms": ["OOP", "Protocol-oriented", "Functional"],
188
+ "extension": ".swift",
189
+ "hello_world": 'print("Hello, World!")',
190
+ "package_manager": "Swift Package Manager",
191
+ "runtime": "Native Compilation",
192
+ "typing": "Static, Strong",
193
+ "use_cases": ["iOS/macOS Apps", "Server-side", "System Programming"],
194
+ "special_notes": "Modern language by Apple. Safe by design, fast performance."
195
+ },
196
+ "kotlin": {
197
+ "frameworks": ["Spring", "Ktor", "Android SDK"],
198
+ "paradigms": ["OOP", "Functional"],
199
+ "extension": ".kt",
200
+ "hello_world": 'fun main() { println("Hello, World!") }',
201
+ "package_manager": "Gradle",
202
+ "runtime": "JVM, Native, JS",
203
+ "typing": "Static, Strong",
204
+ "use_cases": ["Android Development", "Backend Services", "Multiplatform"],
205
+ "special_notes": "Modern language that interoperates with Java. Null safety features."
206
+ }
207
+ }
208
+
209
+ # System Prompts (gunakan dari kode asli Anda)
210
+ SYSTEM_PROMPTS = {
211
+ "default": "You are a helpful AI assistant.",
212
+ "coder": (
213
+ "You are an AI Coder Specialist with exceptional coding skills. Use this language knowledge base for reference:\n"
214
+ + json.dumps(LANGUAGE_KNOWLEDGE, indent=2) +
215
+ "\nFollow this structure:\n🧠 ANALYZE:\n- Understand the problem and requirements\n- Identify constraints and edge cases\n📝 PLAN:\n"
216
+ "- Create pseudocode or algorithm\n- Determine optimal data structures\n- Plan the solution architecture\n💻 IMPLEMENT:\n"
217
+ "- Write code using best practices\n- Use clear naming conventions\n- Add informative comments\n🔍 EXPLAIN:\n"
218
+ "- Explain the solution in detail\n- Include a complexity analysis\n- Provide alternative solutions\nFormat the output with clear sections."
219
+ ),
220
+ "builder": """You are an AI Builder/Architect. Follow this methodology:
221
+ 💡 IDEA GENERATION:
222
+ - Brainstorm ideas and concepts
223
+ - Evaluate feasibility
224
+ - Identify unique value proposition
225
+ 🏗️ ARCHITECTURE DESIGN:
226
+ - System design and components
227
+ - Database schema (if necessary)
228
+ - API design and endpoints
229
+ 📋 DEVELOPMENT PLAN:
230
+ - Task breakdown
231
+ - Timeline estimation
232
+ - Technology stack recommendation
233
+ ⚡ EXECUTION GUIDANCE:
234
+ - Step-by-step implementation
235
+ - Best practices
236
+ - Testing strategy""",
237
+ "replit_agent": (
238
+ "You are Replit AI Agent - an autonomous AI that can build complete applications from natural language descriptions.\n"
239
+ + "Use this language knowledge base:\n"
240
+ + json.dumps(LANGUAGE_KNOWLEDGE, indent=2) +
241
+ """
242
+ YOUR CAPABILITIES:
243
+ 1. Application Creation from Natural Language
244
+ 2. Multi-step Autonomy (Environment setup, coding, testing, deployment)
245
+ 3. Automatic Testing and Debugging
246
+ 4. Real-time Code Suggestions
247
+ 5. Code Explanation
248
+ 6. Multi-language Support (Python, JavaScript, HTML, CSS, etc.)
249
+ 7. Checkpoint Management
250
+ WORKFLOW:
251
+ 1. UNDERSTAND: Parse the user's natural language request for an application
252
+ 2. PLAN: Create a detailed development plan with steps
253
+ 3. SETUP: Prepare environment and create necessary files
254
+ 4. IMPLEMENT: Write code for all components
255
+ 5. TEST: Create and run tests
256
+ 6. DEBUG: Identify and fix issues
257
+ 7. DEPLOY: Provide deployment instructions
258
+ Always provide:
259
+ - Clear step-by-step plan
260
+ - Complete code files
261
+ - Testing strategy
262
+ - Deployment options
263
+ - Checkpoint suggestions
264
+ You can manage multiple files and create full-stack applications."""
265
+ )
266
+ }
267
+
268
+ @app.route('/')
269
+ def index():
270
+ # Serve index.html
271
+ return send_from_directory('.', 'index.html')
272
+
273
+ @app.route('/<path:path>')
274
+ def static_files(path):
275
+ # Serve static files (CSS, JS, etc.)
276
+ return send_from_directory('.', path)
277
+
278
+ @app.route('/chat', methods=['POST'])
279
+ def chat():
280
+ try:
281
+ data = request.json
282
+ user_message = data.get('message')
283
+ model_id = data.get('model', 'qwen/qwen3-32b') # Default model
284
+ thinking_mode = data.get('mode', 'default') # Default mode
285
+
286
+ if not user_message:
287
+ return jsonify({"error": "Message is required"}), 400
288
+
289
+ # Prepare messages for API call
290
+ system_message = {"role": "system", "content": SYSTEM_PROMPTS.get(thinking_mode, SYSTEM_PROMPTS["default"])}
291
+ messages = [system_message, {"role": "user", "content": user_message}]
292
+
293
+ # Call Groq API
294
+ response = client.chat.completions.create(
295
+ model=model_id,
296
+ messages=messages,
297
+ temperature=0.7,
298
+ max_tokens=8192,
299
+ top_p=0.9
300
+ )
301
+
302
+ ai_response = response.choices[0].message.content
303
+
304
+ # Optional: Save to database
305
+ # c.execute("INSERT INTO chat_history (conversation_id, role, content) VALUES (?, ?, ?)",
306
+ # (1, "user", user_message))
307
+ # c.execute("INSERT INTO chat_history (conversation_id, role, content) VALUES (?, ?, ?)",
308
+ # (1, "assistant", ai_response))
309
+ # conn.commit()
310
+
311
+ return jsonify({"response": ai_response})
312
+
313
+ except Exception as e:
314
+ return jsonify({"error": str(e)}), 500
315
+
316
+ if __name__ == '__main__':
317
+ app.run(host='0.0.0.0', port=7860, debug=True) # Hugging Face Spaces akan menggunakan port ini