File size: 4,334 Bytes
c4fe166
ee2bd19
 
c4fe166
ee58796
 
 
c4fe166
ee2bd19
77ea176
c4fe166
ee58796
 
ee2bd19
c1e69c8
ee58796
77ea176
ee58796
 
 
 
 
 
 
 
 
 
 
 
10568f0
ee58796
 
77ea176
 
 
 
10568f0
77ea176
93f8443
77ea176
c1e69c8
77ea176
 
c1e69c8
77ea176
93f8443
77ea176
ee58796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1e69c8
ee58796
 
 
93f8443
10568f0
ee58796
 
 
c1e69c8
ee58796
 
c4fe166
ee58796
c4fe166
ee58796
c4fe166
ee58796
c4fe166
ee58796
c4fe166
 
10568f0
 
fe2220b
c4fe166
10568f0
 
 
 
 
 
 
c56b847
fe2220b
ee58796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1e69c8
93f8443
ee58796
 
86d50cc
ee58796
fe2220b
 
 
 
86d50cc
 
ee58796
 
 
 
 
 
 
 
c1e69c8
 
ee58796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10568f0
 
 
fe2220b
ee58796
c4fe166
ee58796
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import gradio as gr
import requests
import os

# -----------------------------
# GROK SETUP (xAI)
# -----------------------------

API_KEY = os.getenv("XAI_API_KEY")
API_URL = "https://api.x.ai/v1/chat/completions"

if not API_KEY:
    raise ValueError("❌ XAI_API_KEY not set in Hugging Face Secrets")


def call_llm(prompt):
    try:
        headers = {
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        }

        payload = {
            "model": "grok-4-1-fast-non-reasoning",
            "messages": [
                {"role": "system", "content": "You are a helpful AI assistant."},
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.7,
            "max_tokens": 400
        }

        response = requests.post(
            API_URL,
            headers=headers,
            json=payload,
            timeout=30
        )

        data = response.json()

        if "choices" not in data:
            return f"❌ API Error:\n{data}"

        return data["choices"][0]["message"]["content"]

    except Exception as e:
        return f"❌ Request Failed: {str(e)}"


# -----------------------------
# BLOCK LOGIC
# -----------------------------

def create_blocks(text):
    lines = [line.strip() for line in text.split("\n") if line.strip()]
    if not lines:
        lines = ["EMPTY"]

    blocks = [f"{i}: {line}" for i, line in enumerate(lines)]
    return blocks, gr.update(choices=blocks, value=blocks[0])


def select_block(blocks, selected):
    if not blocks or not selected:
        return ""

    idx = int(selected.split(":")[0])
    return blocks[idx].split(": ", 1)[1]


def update_block(blocks, selected, new_text):
    if not blocks or not selected:
        return blocks, gr.update()

    idx = int(selected.split(":")[0])
    blocks[idx] = f"{idx}: {new_text}"

    return blocks, gr.update(choices=blocks, value=blocks[idx])


# -----------------------------
# AI FUNCTIONS
# -----------------------------

# ✨ Rewrite selected block
def ai_rewrite(blocks, selected):
    if not blocks or not selected:
        return blocks, gr.update()

    idx = int(selected.split(":")[0])
    original = blocks[idx].split(": ", 1)[1]

    prompt = f"Rewrite this more clearly and professionally:\n\n{original}"

    new_text = call_llm(prompt)

    blocks[idx] = f"{idx}: {new_text}"

    return blocks, gr.update(choices=blocks, value=blocks[idx])


def ai_rewrite_all(blocks):
    if not blocks:
        return "⚠️ No blocks to rewrite."

    full_text = "\n".join([b.split(": ", 1)[1] for b in blocks])

    prompt = f"""
Rewrite the following text to be clearer, more professional, and well-structured:

{full_text}
"""

    return call_llm(prompt)


# -----------------------------
# UI
# -----------------------------

with gr.Blocks(title="Blocksmith + Grok") as app:

    gr.Markdown("# 🧱 Blocksmith (Powered by Grok)")

    state_blocks = gr.State([])

    input_text = gr.Textbox(label="Paste Text", lines=8)
    create_btn = gr.Button("Create Blocks")

    block_selector = gr.Dropdown(choices=[], label="Blocks", interactive=True)

    block_editor = gr.Textbox(label="Edit Block")

    with gr.Row():
        update_btn = gr.Button("Update")
        rewrite_btn = gr.Button("✨ Rewrite (AI)")
        #rewrite_all_btn = gr.Button("πŸš€ Rewrite All (AI)")

    full_output = gr.Textbox(
        label="Rewritten Full Text",
        lines=10
    )
    rewrite_all_btn = gr.Button("πŸš€ Rewrite All (AI)")
    
    # -----------------------------
    # EVENTS
    # -----------------------------

    create_btn.click(
        fn=create_blocks,
        inputs=input_text,
        outputs=[state_blocks, block_selector]
    )

    block_selector.change(
        fn=select_block,
        inputs=[state_blocks, block_selector],
        outputs=block_editor
    )

    update_btn.click(
        fn=update_block,
        inputs=[state_blocks, block_selector, block_editor],
        outputs=[state_blocks, block_selector]
    )

    rewrite_btn.click(
        fn=ai_rewrite,
        inputs=[state_blocks, block_selector],
        outputs=[state_blocks, block_selector]
    )

    rewrite_all_btn.click(
        fn=ai_rewrite_all,
        inputs=state_blocks,
        outputs=full_output
    )

app.launch()