ChaoticEconomist commited on
Commit
77ea176
·
verified ·
1 Parent(s): ee2bd19

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -126
app.py CHANGED
@@ -2,158 +2,120 @@ import gradio as gr
2
  import requests
3
  import os
4
 
5
- # -----------------------------
6
- # GROK SETUP (xAI)
7
- # -----------------------------
8
 
9
  API_KEY = os.getenv("XAI_API_KEY")
10
 
11
- API_URL = "https://api.x.ai/v1/chat/completions"
12
-
13
- def call_llm(prompt):
14
- try:
15
- headers = {
16
- "Authorization": f"Bearer {API_KEY}",
17
- "Content-Type": "application/json"
18
- }
19
-
20
- payload = {
21
- "model": "grok-beta",
22
- "messages": [
23
- {"role": "user", "content": prompt}
24
- ],
25
- "temperature": 0.7,
26
- "max_tokens": 500
27
- }
28
-
29
- response = requests.post(API_URL, headers=headers, json=payload)
30
- result = response.json()
31
-
32
- return result["choices"][0]["message"]["content"]
33
-
34
- except Exception as e:
35
- return f"ERROR: {str(e)}"
36
-
37
-
38
- # -----------------------------
39
- # BLOCK LOGIC (same as before)
40
- # -----------------------------
41
-
42
- def create_blocks(text):
43
- lines = [line.strip() for line in text.split("\n") if line.strip()]
44
- if not lines:
45
- lines = ["EMPTY"]
46
-
47
- blocks = [f"{i}: {line}" for i, line in enumerate(lines)]
48
- return blocks, gr.update(choices=blocks, value=blocks[0])
49
-
50
-
51
- def select_block(blocks, selected):
52
- if not blocks or not selected:
53
- return ""
54
-
55
- idx = int(selected.split(":")[0])
56
- return blocks[idx].split(": ", 1)[1]
57
-
58
-
59
- def update_block(blocks, selected, new_text):
60
- if not blocks or not selected:
61
- return blocks, gr.update()
62
-
63
- idx = int(selected.split(":")[0])
64
- blocks[idx] = f"{idx}: {new_text}"
65
-
66
- return blocks, gr.update(choices=blocks, value=blocks[idx])
67
 
 
68
 
69
- # -----------------------------
70
- # AI FUNCTIONS (GROK)
71
- # -----------------------------
72
 
73
- def ai_rewrite(blocks, selected):
74
- if not blocks or not selected:
75
- return blocks, gr.update()
76
 
77
- idx = int(selected.split(":")[0])
78
- original = blocks[idx].split(": ", 1)[1]
 
 
 
79
 
80
- prompt = f"Rewrite this more clearly and professionally:\n\n{original}"
 
 
 
 
 
 
 
81
 
82
- new_text = call_llm(prompt)
 
 
 
 
 
 
83
 
84
- blocks[idx] = f"{idx}: {new_text}"
85
 
86
- return blocks, gr.update(choices=blocks, value=blocks[idx])
 
 
87
 
 
88
 
89
- def ai_summarize(blocks, selected):
90
- if not blocks or not selected:
91
- return ""
92
 
93
- idx = int(selected.split(":")[0])
94
- text = blocks[idx].split(": ", 1)[1]
95
 
96
- prompt = f"Summarize this in one concise sentence:\n\n{text}"
 
 
97
 
98
- return call_llm(prompt)
 
 
99
 
 
 
 
100
 
101
- # -----------------------------
102
- # UI
103
- # -----------------------------
104
 
105
- with gr.Blocks(title="Blocksmith + Grok") as app:
 
 
 
 
 
106
 
107
- gr.Markdown("# 🧱 Blocksmith (Powered by Grok)")
 
108
 
109
- state_blocks = gr.State([])
110
 
111
- input_text = gr.Textbox(label="Paste Text", lines=8)
112
- create_btn = gr.Button("Create Blocks")
 
113
 
114
- block_selector = gr.Dropdown(choices=[], label="Blocks", interactive=True)
115
 
116
- block_editor = gr.Textbox(label="Edit Block")
 
 
 
117
 
118
  with gr.Row():
119
- update_btn = gr.Button("Update")
120
- rewrite_btn = gr.Button("✨ Rewrite (AI)")
121
- summarize_btn = gr.Button("🧠 Summarize")
122
-
123
- summary_output = gr.Textbox(label="Summary")
124
-
125
- # -----------------------------
126
- # EVENTS
127
- # -----------------------------
128
-
129
- create_btn.click(
130
- fn=create_blocks,
131
- inputs=input_text,
132
- outputs=[state_blocks, block_selector]
133
- )
134
-
135
- block_selector.change(
136
- fn=select_block,
137
- inputs=[state_blocks, block_selector],
138
- outputs=block_editor
139
- )
140
-
141
- update_btn.click(
142
- fn=update_block,
143
- inputs=[state_blocks, block_selector, block_editor],
144
- outputs=[state_blocks, block_selector]
145
- )
146
-
147
- rewrite_btn.click(
148
- fn=ai_rewrite,
149
- inputs=[state_blocks, block_selector],
150
- outputs=[state_blocks, block_selector]
151
  )
152
 
153
- summarize_btn.click(
154
- fn=ai_summarize,
155
- inputs=[state_blocks, block_selector],
156
- outputs=summary_output
157
- )
158
 
159
- app.launch()
 
 
2
  import requests
3
  import os
4
 
5
+ # =========================
6
+ # CONFIG
7
+ # =========================
8
 
9
  API_KEY = os.getenv("XAI_API_KEY")
10
 
11
+ if not API_KEY:
12
+ raise ValueError("❌ XAI_API_KEY not set. Add it in Hugging Face Secrets.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ API_URL = "https://api.x.ai/v1/chat/completions"
15
 
 
 
 
16
 
17
+ # =========================
18
+ # GROK CALL
19
+ # =========================
20
 
21
+ def call_grok(prompt):
22
+ headers = {
23
+ "Authorization": f"Bearer {API_KEY}",
24
+ "Content-Type": "application/json"
25
+ }
26
 
27
+ payload = {
28
+ "model": "grok-2-latest", # fallback: grok-1
29
+ "messages": [
30
+ {"role": "system", "content": "You are a helpful AI assistant."},
31
+ {"role": "user", "content": prompt}
32
+ ],
33
+ "temperature": 0.7
34
+ }
35
 
36
+ try:
37
+ response = requests.post(
38
+ API_URL,
39
+ headers=headers,
40
+ json=payload,
41
+ timeout=30
42
+ )
43
 
44
+ data = response.json()
45
 
46
+ # 🔴 Handle API errors cleanly
47
+ if "choices" not in data:
48
+ return f"❌ API Error:\n{data}"
49
 
50
+ return data["choices"][0]["message"]["content"]
51
 
52
+ except Exception as e:
53
+ return f"❌ Request Failed:\n{str(e)}"
 
54
 
 
 
55
 
56
+ # =========================
57
+ # BLOCKSMITH LOGIC
58
+ # =========================
59
 
60
+ def generate_blocks(user_input):
61
+ if not user_input.strip():
62
+ return "⚠️ Please enter something."
63
 
64
+ # Simulate your “block” concept
65
+ prompt = f"""
66
+ Break this into structured reasoning blocks:
67
 
68
+ Input:
69
+ {user_input}
 
70
 
71
+ Output format:
72
+ 1. Problem
73
+ 2. Key Ideas
74
+ 3. Solution Steps
75
+ 4. Final Answer
76
+ """
77
 
78
+ result = call_grok(prompt)
79
+ return result
80
 
 
81
 
82
+ # =========================
83
+ # UI (CLEAN + MODERN)
84
+ # =========================
85
 
86
+ with gr.Blocks(theme=gr.themes.Soft(), title="Blocksmith AI") as app:
87
 
88
+ gr.Markdown("""
89
+ # 🧠 Blocksmith AI
90
+ Turn any idea into structured reasoning blocks.
91
+ """)
92
 
93
  with gr.Row():
94
+ with gr.Column(scale=1):
95
+ input_box = gr.Textbox(
96
+ label="Your Input",
97
+ placeholder="Enter a problem, idea, or question...",
98
+ lines=5
99
+ )
100
+
101
+ generate_btn = gr.Button("⚡ Generate Blocks", variant="primary")
102
+
103
+ with gr.Column(scale=1):
104
+ output_box = gr.Textbox(
105
+ label="Structured Output",
106
+ lines=15
107
+ )
108
+
109
+ # 🔥 Button wiring (this is what usually breaks)
110
+ generate_btn.click(
111
+ fn=generate_blocks,
112
+ inputs=input_box,
113
+ outputs=output_box
 
 
 
 
 
 
 
 
 
 
 
 
114
  )
115
 
116
+ # =========================
117
+ # RUN
118
+ # =========================
 
 
119
 
120
+ if __name__ == "__main__":
121
+ app.launch()