giv3me4shot commited on
Commit
2147fdd
·
verified ·
1 Parent(s): de411a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +165 -176
app.py CHANGED
@@ -1,196 +1,185 @@
1
  import gradio as gr
 
2
  import os
3
- import requests
4
- import time
5
-
6
- # Daftar model dengan deskripsi
7
- MODELS_INFO = {
8
- "anthropic/claude-opus-4": {"name": "Claude Opus 4", "description": "Model AI paling canggih Anthropic untuk tugas kompleks"},
9
- "anthropic/claude-sonnet-4": {"name": "Claude Sonnet 4", "description": "Keseimbangan antara kemampuan dan kecepatan"},
10
- "deepseek/deepseek-r1-0528": {"name": "DeepSeek R1", "description": "Model bahasa open-source khusus untuk reasoning"},
11
- "deepseek/deepseek-chat-v3-0324": {"name": "DeepSeek Chat v3", "description": "Dioptimalkan untuk dialog general"},
12
- "openai/gpt-4.1": {"name": "GPT-4.1", "description": "Generasi penyusun teks OpenAI terbaru"},
13
- "openai/gpt-4.1-mini": {"name": "GPT-4.1 Mini", "description": "Versi lebih kecil dan cepat dari GPT-4.1"},
14
- "google/gemini-2.5-pro-preview": {"name": "Gemini 2.5 Pro", "description": "Model Google terbaru untuk pemahaman kompleks"},
15
- "microsoft/phi-4-reasoning-plus": {"name": "Phi-4 Reasoning", "description": "Pakar penalaran matematika dan logika"},
16
- "qwen/qwen3-30b-a3b": {"name": "Qwen 30B", "description": "Model bahasa besar dari China"},
17
- "meta-llama/llama-guard-4-12b": {"name": "Llama Guard 4", "description": "Model khusus untuk moderasi konten"},
18
- "meta-llama/llama-4-maverick": {"name": "Llama 4 Maverick", "description": "Model kreatif untuk penulisan"},
19
- "meta-llama/llama-4-scout": {"name": "Llama 4 Scout", "description": "Direncanakan sebagai penerus Gemini ini"},
20
- "x-ai/grok-2-vision-1212": {"name": "Grok-2 Vision", "description": "Model multimodal X-AI untuk teks dan gambar"}
21
- }
22
 
23
- # Default models list
24
- MODELS = list(MODELS_INFO.keys())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- def chat_with_openrouter(prompt, system_prompt, model):
27
  try:
28
- # Konfigurasi API OpenRouter
29
- api_url = "https://openrouter.ai/api/v1/chat/completions"
30
- api_key = os.environ.get("OPENROUTER_API_KEY")
31
-
32
- # Header untuk autentikasi
33
- headers = {
34
- "Authorization": f"Bearer {api_key}",
35
- "HTTP-Referer": "https://huggingface.co",
36
- "X-Title": "OpenRouter Space",
37
- }
38
-
39
- # Bangun pesan dengan sistem prompt
40
- messages = []
41
- if system_prompt.strip():
42
- messages.append({"role": "system", "content": system_prompt})
43
- messages.append({"role": "user", "content": prompt})
44
-
45
- # Body request
46
- data = {
47
- "model": model,
48
- "messages": messages,
49
- "max_tokens": 2048
50
- }
51
-
52
- start_time = time.time()
53
-
54
- # Kirim request ke OpenRouter
55
- response = requests.post(api_url, headers=headers, json=data, timeout=90)
56
- response.raise_for_status()
57
-
58
- # Ekstrak dan kembalikan respons
59
- result = response.json()
60
 
61
- end_time = time.time()
62
- processing_time = f"\n\n🕒 Waktu pemrosesan: {end_time - start_time:.2f} detik"
 
 
 
 
 
63
 
64
- return result["choices"][0]["message"]["content"] + processing_time
65
-
66
  except Exception as e:
67
- error_detail = f"{str(e)}"
68
- if hasattr(e, 'response') and e.response:
69
- try:
70
- error_resp = e.response.json()
71
- error_detail += f"\nError: {error_resp.get('error', {}).get('message', 'Unknown error')}"
72
- except:
73
- error_detail += f"\nStatus: {e.response.status_code}\nResponse: {e.response.text[:500]}"
74
- return f"🚨 Error: {error_detail}"
75
-
76
- # CSS Styles
77
- with open("style.css", "r") as f:
78
- css_content = f.read()
79
-
80
- # Buat antarmuka Gradio dengan CSS
81
- with gr.Blocks(css=css_content, theme=gr.themes.Soft()) as demo:
82
- gr.Markdown("#app-container", visible=False)
83
-
84
- # Header Section
85
- with gr.Column(elem_classes="header"):
86
- gr.Markdown("""
87
- # 🤖 Advanced AI Chat Assistant
88
- Eksplorasi model AI terbaik melalui OpenRouter
89
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
- # Main Content
92
- with gr.Row(elem_classes="content"):
93
- # Left Controls Panel
94
- with gr.Column(elem_classes="controls"):
95
- with gr.Group(elem_classes="model-selector"):
96
- selected_model = gr.Dropdown(
97
- label="Pilih Model AI",
98
- choices=MODELS,
99
- value="anthropic/claude-opus-4",
100
- interactive=True,
101
- elem_id="model-dropdown"
102
- )
103
-
104
- # Preview model info cards
105
- with gr.Group():
106
- gr.Markdown("### Info Model")
107
- with gr.Row():
108
- for model_id in MODELS:
109
- info = MODELS_INFO[model_id]
110
- with gr.Column(min_width=250):
111
- card = gr.Checkbox(
112
- label=f"**{info['name']}**\n{info['description']}",
113
- value=(model_id == "anthropic/claude-opus-4"),
114
- elem_classes="model-card",
115
- elem_id=f"model-card-{model_id}"
116
- )
117
- card.change(lambda x,m=model_id: m, inputs=[card], outputs=[selected_model])
118
-
119
- with gr.Group(elem_classes="system-prompt-area"):
120
- system_prompt = gr.Textbox(
121
- label="Sistem Prompt (Opsional)",
122
- placeholder="Contoh: 'Anda adalah ahli bahasa Indonesia yang ramah dan membantu'",
123
- lines=5,
124
- max_lines=10
125
- )
126
-
127
- with gr.Group(elem_classes="tips"):
128
- gr.Markdown("### 🚀 Tips Penggunaan")
129
- gr.Markdown("""
130
- - Claude Opus: Terbaik untuk tugas kompleks
131
- - Gemini 2.5: Penalaran kuat dan detail
132
- - GPT-4.1: Kreativi tinggi dan fleksibel
133
- - Llama 4: Variasi fungsi khusus
134
- - **Ctrl+Enter** untuk mengirim prompt
135
- - Gunakan contoh di bawah untuk memulai
136
- """)
137
 
138
- # Right Chat Panel
139
- with gr.Column(elem_classes="chat-container"):
140
- with gr.Column(elem_classes="chat-area"):
141
- with gr.Group(elem_classes="chat-input"):
142
- prompt = gr.Textbox(
143
- label="Pertanyaan/Permintaan",
144
- placeholder="Tulis pesan untuk AI di sini...",
145
- lines=6
146
- )
147
- with gr.Row():
148
- clear_btn = gr.Button("Hapus")
149
- submit_btn = gr.Button("Kirim ke AI", elem_classes="btn-submit")
150
-
151
- with gr.Group(elem_classes="chat-output"):
152
- output = gr.Textbox(
153
- label="Respon AI",
154
- lines=15,
155
- interactive=False
156
- )
157
 
158
- # Kwamples Section
159
- with gr.Group(elem_classes="examples"):
160
- gr.Examples(
161
- examples=[
162
- ["Terjemahkan artikel ilmiah ini ke bahasa Indonesia: [...teks ilmiah...]", "", "openai/gpt-4.1"],
163
- ["Tulis puisi tentang budaya Indonesia dalam gaya Chairil Anwar", "Pakai bahasa Indonesia dengan gaya puisi modern", "anthropic/claude-sonnet-4"],
164
- ["Jelaskan black hole dalam konsep relativitas umum secara sederhana", "Anda adalah profesor astrofisika yang ramah", "google/gemini-2.5-pro-preview"],
165
- ["Ubahlah kode ini menjadi lebih efisien: [contoh kode Python]", "Fokus pada penggunaan memori dan kompleksitas algoritma", "microsoft/phi-4-reasoning-plus"]
166
- ],
167
- inputs=[prompt, system_prompt, selected_model],
168
- label="Contoh Permintaan AI"
169
- )
170
 
171
- # Footer
172
- with gr.Column(elem_classes="footer"):
173
- gr.Markdown("""
174
- ### Dibangun dengan 🤗
175
- Powered by [OpenRouter](https://openrouter.ai) |
176
- [Sumber Daya API](https://openrouter.ai/docs) |
177
- [Statistik Penggunaan](https://openrouter.ai/activity)
178
- """)
179
- gr.HTML("""<img src="https://cdn.myportfolio.com/45200424-090f-478b-9be0-85ca9dee2b39/f3a8a7fb-b385-4a7a-8bee-e325c4b9cf9b_rw_600.png?h=fe0a7278654a29de048391005c6d748f" width="200">""")
180
 
181
  # Event handlers
182
  submit_btn.click(
183
- fn=chat_with_openrouter,
184
- inputs=[prompt, system_prompt, selected_model],
185
  outputs=output
186
  )
187
 
188
- clear_btn.click(lambda: ["", ""], outputs=[prompt, output])
189
-
190
- prompt.submit(
191
- fn=chat_with_openrouter,
192
- inputs=[prompt, system_prompt, selected_model],
193
- outputs=output
194
  )
195
 
196
- demo.launch()
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ # Daftar model yang tersedia
6
+ MODELS = {
7
+ "anthropic/claude-opus-4": "Claude Opus (Anthropic)",
8
+ "anthropic/claude-sonnet-4": "Claude Sonnet (Anthropic)",
9
+ "deepseek/deepseek-r1-0528": "DeepSeek R1",
10
+ "deepseek/deepseek-chat-v3-0324": "DeepSeek Chat",
11
+ "openai/gpt-4.1": "GPT-4.1 (OpenAI)",
12
+ "openai/gpt-4.1-mini": "GPT-4.1 Mini (OpenAI)",
13
+ "google/gemini-2.5-pro-preview": "Gemini 2.5 Pro (Google)",
14
+ "microsoft/phi-4-reasoning-plus": "Phi-4 Reasoning+ (Microsoft)",
15
+ "qwen/qwen3-30b-a3b": "Qwen 30B (Alibaba)",
16
+ "meta-llama/llama-guard-4-12b": "Llama Guard 4 (Meta)",
17
+ "meta-llama/llama-4-maverick": "Llama 4 Maverick (Meta)",
18
+ "meta-llama/llama-4-scout": "Llama 4 Scout (Meta)",
19
+ "x-ai/grok-2-vision-1212": "Grok-2 Vision (xAI)"
20
+ }
21
 
22
+ def predict(model_name, prompt):
23
  try:
24
+ # Inisialisasi pipeline berdasarkan model yang dipilih
25
+ pipe = pipeline(
26
+ "text-generation",
27
+ model=model_name,
28
+ device_map="auto"
29
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ # Generate respons
32
+ outputs = pipe(
33
+ prompt,
34
+ max_new_tokens=256,
35
+ temperature=0.7,
36
+ top_p=0.9
37
+ )
38
 
39
+ return outputs[0]['generated_text']
 
40
  except Exception as e:
41
+ return f"Error: {str(e)}"
42
+
43
+ # CSS kustom untuk antarmuka modern
44
+ custom_css = """
45
+ :root {
46
+ --primary: #4f46e5;
47
+ --secondary: #f9fafb;
48
+ --accent: #8b5cf6;
49
+ --text: #1f2937;
50
+ --border: #e5e7eb;
51
+ }
52
+
53
+ body {
54
+ background: linear-gradient(135deg, #f0f4ff 0%, #fdf2f8 100%);
55
+ font-family: 'Inter', sans-serif;
56
+ }
57
+
58
+ .gr-block {
59
+ background-color: white;
60
+ border-radius: 12px;
61
+ box-shadow: 0 4px 6px rgba(0,0,0,0.05);
62
+ border: 1px solid var(--border);
63
+ }
64
+
65
+ .dark .gr-block {
66
+ background-color: #1a1a2e;
67
+ }
68
+
69
+ h1 {
70
+ text-align: center;
71
+ background: linear-gradient(90deg, var(--primary), var(--accent));
72
+ -webkit-background-clip: text;
73
+ background-clip: text;
74
+ color: transparent;
75
+ font-weight: 800;
76
+ margin-bottom: 20px;
77
+ }
78
+
79
+ .model-selector {
80
+ padding: 20px;
81
+ border-radius: 12px;
82
+ transition: all 0.3s ease;
83
+ }
84
+
85
+ .model-selector:hover {
86
+ transform: translateY(-3px);
87
+ box-shadow: 0 10px 20px rgba(0,0,0,0.1);
88
+ }
89
+
90
+ .centered {
91
+ display: flex;
92
+ justify-content: center;
93
+ gap: 15px;
94
+ flex-wrap: wrap;
95
+ }
96
+
97
+ .model-btn {
98
+ background: white;
99
+ border: 2px solid var(--border);
100
+ border-radius: 8px;
101
+ padding: 12px 20px;
102
+ cursor: pointer;
103
+ transition: all 0.2s;
104
+ font-weight: 500;
105
+ }
106
+
107
+ .model-btn:hover {
108
+ border-color: var(--primary);
109
+ color: var(--primary);
110
+ }
111
+
112
+ .model-btn.active {
113
+ background: var(--primary);
114
+ color: white;
115
+ border-color: var(--primary);
116
+ box-shadow: 0 4px 6px rgba(79, 70, 229, 0.3);
117
+ }
118
+
119
+ footer {
120
+ text-align: center;
121
+ margin-top: 20px;
122
+ color: #6b7280;
123
+ font-size: 0.9em;
124
+ }
125
+ """
126
+
127
+ # Buat komponen Gradio
128
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
129
+ gr.Markdown("# 🤖 Multi-Model AI Playground")
130
+ gr.Markdown("Pilih model AI dan masukkan prompt untuk menghasilkan teks")
131
 
132
+ with gr.Row():
133
+ with gr.Column(scale=3):
134
+ model_selector = gr.Dropdown(
135
+ label="Pilih Model",
136
+ choices=list(MODELS.values()),
137
+ value="Claude Sonnet (Anthropic)"
138
+ )
139
+ prompt = gr.Textbox(
140
+ label="Input Prompt",
141
+ placeholder="Ketik pertanyaan atau instruksi di sini...",
142
+ lines=5
143
+ )
144
+ with gr.Row():
145
+ clear_btn = gr.Button("Hapus")
146
+ submit_btn = gr.Button("Generate", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
+ with gr.Column(scale=2):
149
+ output = gr.Textbox(label="Output", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
+ # Tombol model cepat
152
+ gr.Markdown("### Model Populer:")
153
+ with gr.Row(elem_classes="centered"):
154
+ for model_id, model_name in list(MODELS.items())[:5]:
155
+ gr.Button(
156
+ model_name.split("(")[0].strip(),
157
+ elem_classes="model-btn"
158
+ ).click(
159
+ fn=lambda m=model_name: m,
160
+ inputs=[],
161
+ outputs=model_selector
162
+ )
163
 
164
+ gr.Markdown("---")
165
+ gr.Markdown("""
166
+ <div style="text-align: center">
167
+ <small>Powered by Hugging Face Spaces | Model tersedia melalui API</small>
168
+ </div>
169
+ """)
 
 
 
170
 
171
  # Event handlers
172
  submit_btn.click(
173
+ fn=lambda m, p: predict(list(MODELS.keys())[list(MODELS.values()).index(m)], p),
174
+ inputs=[model_selector, prompt],
175
  outputs=output
176
  )
177
 
178
+ clear_btn.click(
179
+ fn=lambda: ["", ""],
180
+ inputs=[],
181
+ outputs=[prompt, output]
 
 
182
  )
183
 
184
+ if __name__ == "__main__":
185
+ demo.launch()