Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -13,6 +13,7 @@ import shutil
|
|
| 13 |
import traceback
|
| 14 |
import json
|
| 15 |
from typing import List, Tuple, Optional, Dict
|
|
|
|
| 16 |
|
| 17 |
# Clean up any existing temp files on startup to save space
|
| 18 |
try:
|
|
@@ -321,6 +322,27 @@ def install_packages_if_needed(packages):
|
|
| 321 |
|
| 322 |
return len(failed_packages) == 0
|
| 323 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
def generate_code_with_openrouter(instruction, file_paths, previous_errors=None, attempt=1):
|
| 325 |
"""Generate Python code using OpenRouter API with error awareness."""
|
| 326 |
|
|
@@ -555,13 +577,31 @@ def execute_code_with_retry(code: str, max_attempts: int = 3) -> Tuple[bool, str
|
|
| 555 |
|
| 556 |
return False, "Max attempts reached", None
|
| 557 |
|
| 558 |
-
def process_request(instruction, files):
|
| 559 |
-
"""Main processing function with self-correction"""
|
| 560 |
try:
|
| 561 |
if not instruction.strip():
|
| 562 |
-
return "لطفاً دستور را وارد کنید. (فایلها اختیاری هستند)", None
|
|
|
|
|
|
|
| 563 |
|
| 564 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 565 |
|
| 566 |
# Track errors for learning
|
| 567 |
previous_errors = []
|
|
@@ -640,6 +680,8 @@ with gr.Blocks(title="AI File Processor - Self Correcting") as demo:
|
|
| 640 |
- "یک فایل اکسل با 1000 نام و شماره تلفن ایرانی بساز"
|
| 641 |
- "پسزمینه این تصویر را حذف کن"
|
| 642 |
- "این فایل CSV را به JSON تبدیل کن"
|
|
|
|
|
|
|
| 643 |
""")
|
| 644 |
|
| 645 |
with gr.Row():
|
|
@@ -649,7 +691,14 @@ with gr.Blocks(title="AI File Processor - Self Correcting") as demo:
|
|
| 649 |
placeholder="مثال: یک نمودار دایرهای از دادههای فروش بکش",
|
| 650 |
rtl=True
|
| 651 |
)
|
| 652 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 653 |
|
| 654 |
btn = gr.Button("🚀 اجرا", variant="primary")
|
| 655 |
|
|
@@ -660,14 +709,15 @@ with gr.Blocks(title="AI File Processor - Self Correcting") as demo:
|
|
| 660 |
# Examples
|
| 661 |
gr.Examples(
|
| 662 |
examples=[
|
| 663 |
-
["یک فایل اکسل با 100 محصول فروشگاهی شامل نام، قیمت و موجودی بساز",
|
| 664 |
-
["یک نمودار میلهای از دادههای تصادفی رسم کن",
|
| 665 |
-
["یک تصویر 500x500 پیکسل با رنگهای تصادفی بساز",
|
|
|
|
| 666 |
],
|
| 667 |
-
inputs=[instruction, files],
|
| 668 |
)
|
| 669 |
|
| 670 |
-
btn.click(fn=process_request, inputs=[instruction, files], outputs=[output, file_out])
|
| 671 |
|
| 672 |
if __name__ == "__main__":
|
| 673 |
-
demo.launch(share=True)
|
|
|
|
| 13 |
import traceback
|
| 14 |
import json
|
| 15 |
from typing import List, Tuple, Optional, Dict
|
| 16 |
+
import requests # Added for downloading from URLs
|
| 17 |
|
| 18 |
# Clean up any existing temp files on startup to save space
|
| 19 |
try:
|
|
|
|
| 322 |
|
| 323 |
return len(failed_packages) == 0
|
| 324 |
|
| 325 |
+
def download_file_from_url(url: str, temp_dir: str) -> Optional[str]:
|
| 326 |
+
"""Download a file from URL to temp_dir and return local path."""
|
| 327 |
+
try:
|
| 328 |
+
filename = url.split('/')[-1].split('?')[0] or 'downloaded_file'
|
| 329 |
+
if '.' not in filename:
|
| 330 |
+
filename += '.txt' # Default extension
|
| 331 |
+
local_path = os.path.join(temp_dir, filename)
|
| 332 |
+
|
| 333 |
+
response = requests.get(url, stream=True, timeout=30)
|
| 334 |
+
response.raise_for_status()
|
| 335 |
+
|
| 336 |
+
with open(local_path, 'wb') as f:
|
| 337 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 338 |
+
f.write(chunk)
|
| 339 |
+
|
| 340 |
+
print(f"Downloaded {url} to {local_path}")
|
| 341 |
+
return local_path
|
| 342 |
+
except Exception as e:
|
| 343 |
+
print(f"Failed to download {url}: {e}")
|
| 344 |
+
return None
|
| 345 |
+
|
| 346 |
def generate_code_with_openrouter(instruction, file_paths, previous_errors=None, attempt=1):
|
| 347 |
"""Generate Python code using OpenRouter API with error awareness."""
|
| 348 |
|
|
|
|
| 577 |
|
| 578 |
return False, "Max attempts reached", None
|
| 579 |
|
| 580 |
+
def process_request(instruction, files, urls_input):
|
| 581 |
+
"""Main processing function with self-correction, supporting URLs."""
|
| 582 |
try:
|
| 583 |
if not instruction.strip():
|
| 584 |
+
return "لطفاً دستور را وارد کنید. (فایلها و لینکها اختیاری هستند)", None
|
| 585 |
+
|
| 586 |
+
file_paths = []
|
| 587 |
|
| 588 |
+
# Handle uploaded files
|
| 589 |
+
if files:
|
| 590 |
+
file_paths = [f.name for f in files]
|
| 591 |
+
|
| 592 |
+
# Handle URLs: download to temp dir
|
| 593 |
+
if urls_input and urls_input.strip():
|
| 594 |
+
temp_dir_for_downloads = tempfile.mkdtemp(prefix='url_downloads_')
|
| 595 |
+
urls = [url.strip() for url in urls_input.split(',') if url.strip()]
|
| 596 |
+
downloaded_paths = []
|
| 597 |
+
for url in urls:
|
| 598 |
+
local_path = download_file_from_url(url, temp_dir_for_downloads)
|
| 599 |
+
if local_path:
|
| 600 |
+
downloaded_paths.append(local_path)
|
| 601 |
+
file_paths.extend(downloaded_paths)
|
| 602 |
+
print(f"Downloaded {len(downloaded_paths)} files from URLs")
|
| 603 |
+
|
| 604 |
+
# Clean up note: Temp dirs will be cleaned on shutdown or manually if needed
|
| 605 |
|
| 606 |
# Track errors for learning
|
| 607 |
previous_errors = []
|
|
|
|
| 680 |
- "یک فایل اکسل با 1000 نام و شماره تلفن ایرانی بساز"
|
| 681 |
- "پسزمینه این تصویر را حذف کن"
|
| 682 |
- "این فایل CSV را به JSON تبدیل کن"
|
| 683 |
+
|
| 684 |
+
**نکته:** میتوانید فایلها را آپلود کنید یا لینکهای فایل را (جدا شده با کاما) وارد کنید.
|
| 685 |
""")
|
| 686 |
|
| 687 |
with gr.Row():
|
|
|
|
| 691 |
placeholder="مثال: یک نمودار دایرهای از دادههای فروش بکش",
|
| 692 |
rtl=True
|
| 693 |
)
|
| 694 |
+
|
| 695 |
+
with gr.Row():
|
| 696 |
+
files = gr.File(file_count="multiple", label="فایلهای آپلود شده (اختیاری)")
|
| 697 |
+
urls = gr.Textbox(
|
| 698 |
+
label="لینک فایلها (جدا با کاما، اختیاری)",
|
| 699 |
+
placeholder="https://example.com/file1.csv, https://example.com/file2.jpg",
|
| 700 |
+
info="لینکها دانلود خواهند شد و حجم فایل چک نمیشود."
|
| 701 |
+
)
|
| 702 |
|
| 703 |
btn = gr.Button("🚀 اجرا", variant="primary")
|
| 704 |
|
|
|
|
| 709 |
# Examples
|
| 710 |
gr.Examples(
|
| 711 |
examples=[
|
| 712 |
+
["یک فایل اکسل با 100 محصول فروشگاهی شامل نام، قیمت و موجودی بساز", None, None],
|
| 713 |
+
["یک نمودار میلهای از دادههای تصادفی رسم کن", None, None],
|
| 714 |
+
["یک تصویر 500x500 پیکسل با رنگهای تصادفی بساز", None, None],
|
| 715 |
+
["این فایل را به فرمت JSON تبدیل کن", None, "https://example.com/sample.csv"],
|
| 716 |
],
|
| 717 |
+
inputs=[instruction, files, urls],
|
| 718 |
)
|
| 719 |
|
| 720 |
+
btn.click(fn=process_request, inputs=[instruction, files, urls], outputs=[output, file_out])
|
| 721 |
|
| 722 |
if __name__ == "__main__":
|
| 723 |
+
demo.launch(share=True)
|