Felguk commited on
Commit
0f1db3b
·
verified ·
1 Parent(s): e7fcdc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -26
app.py CHANGED
@@ -3,6 +3,8 @@ import requests
3
  from urllib.parse import urlparse, urljoin
4
  from bs4 import BeautifulSoup
5
  import asyncio
 
 
6
 
7
  # HTML and JavaScript for the "Copy Code" button
8
  copy_button_html = """
@@ -173,26 +175,65 @@ async def fetch_space_file_content(space_url, file_path):
173
  except Exception as e:
174
  return f"Error: {e}"
175
 
176
- # Perchance to Text Converter
177
- async def fetch_perchance_text(perchance_url):
178
- """Fetches the text content from a Perchance application."""
179
  try:
180
- # Fetch the HTML content of the Perchance page
181
- response = await asyncio.to_thread(requests.get, perchance_url, timeout=5)
182
- response.raise_for_status()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
- # Parse the HTML content
185
- soup = BeautifulSoup(response.text, "html.parser")
 
 
 
 
 
186
 
187
- # Extract the text content of the Perchance application
188
- # Assuming the main content is inside a <div> with a specific class or id
189
- # You may need to inspect the page to find the correct selector
190
- main_content = soup.find("div", {"class": "perchance-app"}) # Adjust the selector as needed
191
 
192
- if main_content:
193
- return main_content.get_text(strip=True)
194
- else:
195
- return "Error: Could not find the Perchance application content."
 
 
 
 
 
 
 
 
 
196
  except Exception as e:
197
  return f"Error: {e}"
198
 
@@ -245,6 +286,17 @@ with gr.Blocks() as demo:
245
  gr.Markdown("### JS Content")
246
  js_content_output = gr.Textbox(label="JS Content", interactive=True)
247
 
 
 
 
 
 
 
 
 
 
 
 
248
  # Tab 2: Model to Text Converter
249
  with gr.Tab("Model to Text Converter"):
250
  gr.Markdown("## Model to Text Converter")
@@ -291,6 +343,20 @@ with gr.Blocks() as demo:
291
  with gr.Row():
292
  gr.HTML("<button onclick='copyCode(\"space-content-output\")'>Copy Code</button>") # Add the "Copy Code" button
293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  submit_space_button = gr.Button("Fetch File Content")
295
  submit_space_button.click(
296
  fn=fetch_space_file_content,
@@ -298,25 +364,25 @@ with gr.Blocks() as demo:
298
  outputs=[space_content_output]
299
  )
300
 
301
- # Tab 4: Perchance to Text Converter
302
- with gr.Tab("Perchance to Text Converter"):
303
- gr.Markdown("## Perchance to Text Converter")
304
- gr.Markdown("Enter a link to a Perchance application to fetch its text content.")
305
 
306
  with gr.Row():
307
- perchance_url_input = gr.Textbox(label="Perchance URL", placeholder="https://perchance.org/...")
308
 
309
  with gr.Row():
310
- perchance_content_output = gr.Textbox(label="Text Content", interactive=True, elem_id="perchance-content-output")
311
 
312
  with gr.Row():
313
- gr.HTML("<button onclick='copyCode(\"perchance-content-output\")'>Copy Code</button>") # Add the "Copy Code" button
314
 
315
- submit_perchance_button = gr.Button("Fetch Text Content")
316
  submit_perchance_button.click(
317
- fn=fetch_perchance_text,
318
  inputs=perchance_url_input,
319
- outputs=perchance_content_output
320
  )
321
 
322
  # Launch the interface
 
3
  from urllib.parse import urlparse, urljoin
4
  from bs4 import BeautifulSoup
5
  import asyncio
6
+ import subprocess
7
+ from playwright.async_api import async_playwright
8
 
9
  # HTML and JavaScript for the "Copy Code" button
10
  copy_button_html = """
 
175
  except Exception as e:
176
  return f"Error: {e}"
177
 
178
+ # Function to check code for errors and provide detailed feedback
179
+ def check_code_for_errors(code):
180
+ """Checks the code for errors using flake8 and provides detailed feedback."""
181
  try:
182
+ # Run flake8 to check for errors
183
+ result = subprocess.run(
184
+ ["flake8", "--stdin-display-name", "app.py", "-"],
185
+ input=code.encode(),
186
+ capture_output=True,
187
+ text=True,
188
+ )
189
+
190
+ if result.returncode == 0:
191
+ return "No errors found in the code.", code
192
+
193
+ # If there are errors, parse the output and provide detailed feedback
194
+ errors = result.stderr if result.stderr else result.stdout
195
+ error_messages = []
196
+ for line in errors.splitlines():
197
+ if ":" in line:
198
+ parts = line.split(":")
199
+ if len(parts) >= 4:
200
+ file_name, line_number, column, message = parts[0], parts[1], parts[2], ":".join(parts[3:])
201
+ error_messages.append(f"Line {line_number}, Column {column}: {message.strip()}")
202
+
203
+ if not error_messages:
204
+ return "Errors found, but could not parse details.", code
205
+
206
+ detailed_feedback = "Errors found in the code:\n" + "\n".join(error_messages)
207
+ return detailed_feedback, code
208
+ except Exception as e:
209
+ return f"Error: {e}", code
210
 
211
+ # Perchance.org to Code Converter
212
+ async def fetch_perchance_code(perchance_url):
213
+ """Fetches the code from a Perchance.org generator using Playwright."""
214
+ try:
215
+ # Проверка, что URL принадлежит Perchance.org
216
+ if not perchance_url.startswith("https://perchance.org/"):
217
+ return "Error: Please enter a valid Perchance.org URL."
218
 
219
+ async with async_playwright() as p:
220
+ # Запуск браузера
221
+ browser = await p.chromium.launch(headless=True)
222
+ page = await browser.new_page()
223
 
224
+ # Переход на страницу
225
+ await page.goto(perchance_url, wait_until="networkidle")
226
+
227
+ # Ожидание загрузки текстового поля с кодом
228
+ await page.wait_for_selector("textarea#editBox", state="visible")
229
+
230
+ # Извлечение кода
231
+ code = await page.evaluate('document.querySelector("textarea#editBox").value')
232
+
233
+ # Закрытие браузера
234
+ await browser.close()
235
+
236
+ return code if code else "Error: Could not find the code in the generator."
237
  except Exception as e:
238
  return f"Error: {e}"
239
 
 
286
  gr.Markdown("### JS Content")
287
  js_content_output = gr.Textbox(label="JS Content", interactive=True)
288
 
289
+ # Add image previews
290
+ gr.Markdown("### Image Previews")
291
+ image_previews = gr.Gallery(label="Image Previews")
292
+
293
+ # Update the image previews
294
+ submit_button.click(
295
+ fn=lambda img_links: [requests.get(link).content for link in img_links],
296
+ inputs=img_output,
297
+ outputs=image_previews
298
+ )
299
+
300
  # Tab 2: Model to Text Converter
301
  with gr.Tab("Model to Text Converter"):
302
  gr.Markdown("## Model to Text Converter")
 
343
  with gr.Row():
344
  gr.HTML("<button onclick='copyCode(\"space-content-output\")'>Copy Code</button>") # Add the "Copy Code" button
345
 
346
+ # Кнопка Correcter
347
+ correcter_button = gr.Button("Correcter")
348
+
349
+ # Обработчик для кнопки Correcter
350
+ def correct_code_handler(code):
351
+ result, corrected_code = check_code_for_errors(code)
352
+ return result, corrected_code
353
+
354
+ correcter_button.click(
355
+ fn=correct_code_handler,
356
+ inputs=space_content_output,
357
+ outputs=[gr.Textbox(label="Correction Result"), space_content_output]
358
+ )
359
+
360
  submit_space_button = gr.Button("Fetch File Content")
361
  submit_space_button.click(
362
  fn=fetch_space_file_content,
 
364
  outputs=[space_content_output]
365
  )
366
 
367
+ # Tab 4: Perchance.org to Code Converter
368
+ with gr.Tab("Perchance.org to Code Converter"):
369
+ gr.Markdown("## Perchance.org to Code Converter")
370
+ gr.Markdown("Enter a link to a Perchance.org generator to extract its code.")
371
 
372
  with gr.Row():
373
+ perchance_url_input = gr.Textbox(label="Perchance.org URL", placeholder="https://perchance.org/[name]#edit")
374
 
375
  with gr.Row():
376
+ perchance_code_output = gr.Textbox(label="Generator Code", interactive=True, elem_id="perchance-code-output")
377
 
378
  with gr.Row():
379
+ gr.HTML("<button onclick='copyCode(\"perchance-code-output\")'>Copy Code</button>") # Add the "Copy Code" button
380
 
381
+ submit_perchance_button = gr.Button("Fetch Code")
382
  submit_perchance_button.click(
383
+ fn=fetch_perchance_code,
384
  inputs=perchance_url_input,
385
+ outputs=perchance_code_output
386
  )
387
 
388
  # Launch the interface