SlouchyBuffalo commited on
Commit
ce2dbd2
Β·
verified Β·
1 Parent(s): 10d8a94

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +368 -136
app.py CHANGED
@@ -1,154 +1,386 @@
 
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
-
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
- import torch
8
-
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
  }
65
- """
66
 
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
 
 
70
 
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
 
80
- run_button = gr.Button("Run", scale=0, variant="primary")
 
 
 
 
 
81
 
82
- result = gr.Image(label="Result", show_label=False)
 
 
 
 
 
83
 
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
 
 
 
 
 
91
 
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
- )
99
 
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
 
 
 
 
 
 
 
 
101
 
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
 
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  )
118
-
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
  )
127
-
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
- )
152
-
153
  if __name__ == "__main__":
154
- demo.launch()
 
1
+ # app.py - Complete ZeroGPU Pages Converter
2
  import gradio as gr
3
+ import os
4
+ import spaces
5
+ import tempfile
6
+ import zipfile
7
+ import json
8
+ from pathlib import Path
9
+ from huggingface_hub import InferenceClient
10
+ import xml.etree.ElementTree as ET
11
+ import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # Initialize the Cerebras model client
14
+ client = InferenceClient(
15
+ model="cerebras/llama-3.3-70b-instruct",
16
+ token=os.getenv("HF_TOKEN") # Space secret
17
+ )
18
+
19
+ @spaces.GPU
20
+ def extract_pages_content(file_path):
21
+ """Extract content from Apple Pages file using ZeroGPU"""
22
+ try:
23
+ content_parts = []
24
+
25
+ with zipfile.ZipFile(file_path, 'r') as zip_ref:
26
+ with tempfile.TemporaryDirectory() as temp_dir:
27
+ zip_ref.extractall(temp_dir)
28
+ temp_path = Path(temp_dir)
29
+
30
+ # Strategy 1: Look for index.xml (main document structure)
31
+ index_xml = temp_path / "index.xml"
32
+ if index_xml.exists():
33
+ content = parse_index_xml(index_xml)
34
+ if content:
35
+ return content
36
+
37
+ # Strategy 2: Search all XML files
38
+ for xml_file in temp_path.rglob("*.xml"):
39
+ try:
40
+ tree = ET.parse(xml_file)
41
+ root = tree.getroot()
42
+
43
+ # Extract all text content
44
+ for elem in root.iter():
45
+ if elem.text and elem.text.strip():
46
+ content_parts.append(elem.text.strip())
47
+ except:
48
+ continue
49
+
50
+ # Strategy 3: Look for json files with content
51
+ for json_file in temp_path.rglob("*.json"):
52
+ try:
53
+ with open(json_file, 'r', encoding='utf-8') as f:
54
+ data = json.load(f)
55
+ # Extract text from json recursively
56
+ extract_text_from_json(data, content_parts)
57
+ except:
58
+ continue
59
+
60
+ if content_parts:
61
+ # Clean and deduplicate
62
+ unique_content = list(dict.fromkeys(content_parts))
63
+ return "\n\n".join(unique_content)
64
+ else:
65
+ return "Could not extract readable content from .pages file"
66
+
67
+ except Exception as e:
68
+ return f"Error extracting content: {str(e)}"
69
+
70
+ def parse_index_xml(xml_file):
71
+ """Parse the main index.xml file for document structure"""
72
+ try:
73
+ tree = ET.parse(xml_file)
74
+ root = tree.getroot()
75
+
76
+ content_parts = []
77
+
78
+ # Look for specific Pages XML structure
79
+ # Pages files often have content in specific elements
80
+ for elem in root.iter():
81
+ # Extract text from various element types
82
+ if elem.text and elem.text.strip():
83
+ text = elem.text.strip()
84
+ # Avoid adding very short fragments
85
+ if len(text) > 5:
86
+ content_parts.append(text)
87
+
88
+ return "\n".join(content_parts) if content_parts else None
89
+ except:
90
+ return None
91
+
92
+ def extract_text_from_json(obj, content_parts):
93
+ """Recursively extract text from JSON objects"""
94
+ if isinstance(obj, dict):
95
+ for value in obj.values():
96
+ extract_text_from_json(value, content_parts)
97
+ elif isinstance(obj, list):
98
+ for item in obj:
99
+ extract_text_from_json(item, content_parts)
100
+ elif isinstance(obj, str) and obj.strip() and len(obj.strip()) > 5:
101
+ content_parts.append(obj.strip())
102
+
103
+ @spaces.GPU
104
+ def convert_pages_document(file, output_format, progress=gr.Progress()):
105
+ """Convert Pages document using Cerebras with ZeroGPU acceleration"""
106
+ if not file:
107
+ return None, "❌ Please upload a .pages file"
108
+
109
+ try:
110
+ progress(0.1, desc="πŸ“– Extracting content from .pages file...")
111
+
112
+ # Extract content
113
+ content = extract_pages_content(file.name)
114
+
115
+ if not content or len(content.strip()) < 10:
116
+ return None, "❌ Could not extract sufficient content from .pages file"
117
+
118
+ progress(0.4, desc="πŸ€– Preparing conversion with Cerebras...")
119
+
120
+ # Create format-specific prompt
121
+ prompt = create_conversion_prompt(content, output_format)
122
+
123
+ progress(0.6, desc="⚑ Converting with Cerebras Lightning Speed...")
124
+
125
+ # Convert using Cerebras (lightning fast!)
126
+ response = client.text_generation(
127
+ prompt,
128
+ max_new_tokens=4096,
129
+ temperature=0.1,
130
+ do_sample=False,
131
+ return_full_text=False,
132
+ stop_sequences=None
133
+ )
134
+
135
+ progress(0.9, desc="πŸ’« Creating output file...")
136
+
137
+ # Create output file
138
+ output_path = create_output_file(response, output_format)
139
+
140
+ progress(1.0, desc="βœ… Conversion complete!")
141
+
142
+ return output_path, f"βœ… Successfully converted to {output_format} using ZeroGPU!"
143
+
144
+ except Exception as e:
145
+ return None, f"❌ Error: {str(e)}"
146
+
147
+ def create_conversion_prompt(content, output_format):
148
+ """Create optimized prompt for Cerebras model"""
149
+ format_instructions = {
150
+ "PDF": "Create content suitable for PDF format with proper structure and formatting",
151
+ "DOCX": "Format as Microsoft Word document with headers, paragraphs, and proper styling",
152
+ "TXT": "Convert to clean, readable plain text preserving structure",
153
+ "HTML": "Create well-structured HTML with semantic markup",
154
+ "Markdown": "Convert to properly formatted Markdown with headers and structure"
155
+ }
156
+
157
+ return f"""You are an expert document converter. Convert the following Apple Pages document content to {output_format} format.
158
+
159
+ INSTRUCTIONS:
160
+ 1. Preserve the original structure, formatting, and content organization
161
+ 2. Maintain headings, paragraphs, lists, and any tables if present
162
+ 3. Ensure the output is clean, professional, and well-formatted
163
+ 4. {format_instructions.get(output_format, "Format appropriately for the requested output type")}
164
+ 5. Return ONLY the converted content without explanations or meta-commentary
165
+
166
+ ORIGINAL CONTENT:
167
+ {content}
168
+
169
+ CONVERTED {output_format.upper()} OUTPUT:"""
170
+
171
+ def create_output_file(content, output_format):
172
+ """Create output file in specified format"""
173
+ # Clean the content (remove potential prompt artifacts)
174
+ content = content.strip()
175
+
176
+ # Create temporary file with appropriate extension
177
+ extensions = {
178
+ "PDF": ".html", # HTML for PDF compatibility
179
+ "DOCX": ".html", # HTML for Word compatibility
180
+ "TXT": ".txt",
181
+ "HTML": ".html",
182
+ "Markdown": ".md"
183
+ }
184
+
185
+ ext = extensions.get(output_format, ".txt")
186
+
187
+ with tempfile.NamedTemporaryFile(mode='w', suffix=ext, delete=False, encoding='utf-8') as f:
188
+ if output_format in ["PDF", "DOCX"] and not content.startswith('<'):
189
+ # Wrap plain text in HTML for better compatibility
190
+ f.write(f"""<!DOCTYPE html>
191
+ <html>
192
+ <head>
193
+ <meta charset="UTF-8">
194
+ <title>Converted Document</title>
195
+ <style>
196
+ body {{ font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; }}
197
+ h1, h2, h3 {{ color: #333; }}
198
+ p {{ margin-bottom: 1em; }}
199
+ </style>
200
+ </head>
201
+ <body>
202
+ <pre style="white-space: pre-wrap; font-family: Arial, sans-serif;">{content}</pre>
203
+ </body>
204
+ </html>""")
205
+ else:
206
+ f.write(content)
207
+
208
+ return f.name
209
+
210
+ # Custom CSS for professional appearance
211
  css = """
212
+ .gradio-container {
213
+ background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
214
+ min-height: 100vh;
215
  }
 
216
 
217
+ .main-content {
218
+ max-width: 1000px;
219
+ margin: 0 auto;
220
+ padding: 2rem;
221
+ }
222
 
223
+ .hero-section {
224
+ background: white;
225
+ border-radius: 1rem;
226
+ padding: 2rem;
227
+ text-align: center;
228
+ box-shadow: 0 10px 30px rgba(0,0,0,0.1);
229
+ margin-bottom: 2rem;
230
+ }
231
 
232
+ .upload-section {
233
+ background: white;
234
+ border-radius: 1rem;
235
+ padding: 2rem;
236
+ box-shadow: 0 5px 15px rgba(0,0,0,0.1);
237
+ }
238
 
239
+ .format-selector {
240
+ background: #f8f9fa;
241
+ border-radius: 0.5rem;
242
+ padding: 1rem;
243
+ margin: 1rem 0;
244
+ }
245
 
246
+ .convert-button {
247
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
248
+ color: white;
249
+ border: none;
250
+ padding: 1rem 2rem;
251
+ border-radius: 0.5rem;
252
+ font-size: 1.1rem;
253
+ font-weight: bold;
254
+ width: 100%;
255
+ cursor: pointer;
256
+ transition: all 0.3s ease;
257
+ }
258
 
259
+ .convert-button:hover {
260
+ transform: translateY(-2px);
261
+ box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
262
+ }
 
 
 
263
 
264
+ .zerogpu-badge {
265
+ display: inline-block;
266
+ background: linear-gradient(45deg, #ff6b6b, #feca57);
267
+ color: white;
268
+ padding: 0.5rem 1rem;
269
+ border-radius: 2rem;
270
+ font-weight: bold;
271
+ font-size: 0.9rem;
272
+ }
273
 
274
+ .pro-features {
275
+ background: #e8f5e9;
276
+ border-radius: 0.5rem;
277
+ padding: 1rem;
278
+ margin-top: 1rem;
279
+ }
280
+ """
 
281
 
282
+ # Create the Gradio interface
283
+ with gr.Blocks(css=css, title="Pages Converter Pro - ZeroGPU", theme=gr.themes.Soft()) as app:
284
+ with gr.Column(elem_classes=["main-content"]):
285
+ # Hero section
286
+ gr.HTML("""
287
+ <div class="hero-section">
288
+ <h1>πŸ“„ Pages Converter Pro</h1>
289
+ <span class="zerogpu-badge">⚑ ZeroGPU Accelerated</span>
290
+ <p style="margin-top: 1rem; color: #666;">
291
+ Convert Apple Pages documents with lightning-fast Cerebras Llama-3.3-70B
292
+ </p>
293
+ </div>
294
+ """)
295
+
296
+ # Pro benefits showcase
297
+ gr.HTML("""
298
+ <div class="pro-features">
299
+ <h3>πŸš€ HuggingFace Pro Benefits Active</h3>
300
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-top: 1rem;">
301
+ <div>βœ… 5x Usage Quota</div>
302
+ <div>πŸ”₯ Priority Queue Access</div>
303
+ <div>πŸ’Ž H200 GPU Hardware</div>
304
+ <div>⚑ Zero-GPU Acceleration</div>
305
+ </div>
306
+ </div>
307
+ """)
308
+
309
+ # Main conversion interface
310
+ with gr.Row():
311
+ with gr.Column(scale=2, elem_classes=["upload-section"]):
312
+ gr.HTML("<h3>πŸ“Ž Upload Your Document</h3>")
313
+
314
+ file_input = gr.File(
315
+ label="Select .pages file",
316
+ file_types=[".pages"],
317
+ elem_id="file-upload"
318
  )
319
+
320
+ output_format = gr.Radio(
321
+ choices=["PDF", "DOCX", "TXT", "HTML", "Markdown"],
322
+ value="PDF",
323
+ label="🎯 Output Format",
324
+ elem_classes=["format-selector"]
 
 
325
  )
326
+
327
+ convert_btn = gr.Button(
328
+ "⚑ Convert with ZeroGPU",
329
+ variant="primary",
330
+ elem_classes=["convert-button"]
 
 
331
  )
332
+
333
+ with gr.Column(scale=1):
334
+ gr.HTML("""
335
+ <div style="background: white; padding: 1.5rem; border-radius: 1rem; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
336
+ <h3>⚑ ZeroGPU Features</h3>
337
+ <ul style="color: #666;">
338
+ <li>Lightning-fast processing</li>
339
+ <li>H200 hardware acceleration</li>
340
+ <li>Priority queue access</li>
341
+ <li>Cerebras optimization</li>
342
+ </ul>
343
+
344
+ <h3>πŸ“‹ Supported Formats</h3>
345
+ <ul style="color: #666;">
346
+ <li>πŸ“„ PDF (best quality)</li>
347
+ <li>πŸ“ Microsoft Word (DOCX)</li>
348
+ <li>πŸ“‹ Plain Text (TXT)</li>
349
+ <li>🌐 Web Page (HTML)</li>
350
+ <li>✏️ Markdown (MD)</li>
351
+ </ul>
352
+ </div>
353
+ """)
354
+
355
+ # Output section
356
+ with gr.Row():
357
+ output_file = gr.File(
358
+ label="πŸ“ Download Your Converted File",
359
+ elem_id="output-download"
360
+ )
361
+
362
+ with gr.Row():
363
+ status_html = gr.HTML(
364
+ value="<div style='text-align: center; padding: 1rem; color: #666;'>Ready to convert your Pages document</div>",
365
+ elem_id="status-display"
366
+ )
367
+
368
+ # Connect the interface
369
+ convert_btn.click(
370
+ fn=convert_pages_document,
371
+ inputs=[file_input, output_format],
372
+ outputs=[output_file, status_html],
373
+ show_progress=True
374
+ )
375
+
376
+ # Footer
377
+ gr.HTML("""
378
+ <div style="text-align: center; margin-top: 3rem; padding: 2rem; color: white;">
379
+ <p>πŸ’Ž Built exclusively for HuggingFace Pro users</p>
380
+ <p><small>Powered by Cerebras β€’ Accelerated by ZeroGPU β€’ Made with ❀️</small></p>
381
+ </div>
382
+ """)
383
 
384
+ # Launch the app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
  if __name__ == "__main__":
386
+ app.launch()