Spaces:
Running
Running
add file upload support
Browse files- app.py +44 -3
- requirements.txt +3 -1
app.py
CHANGED
@@ -3,6 +3,9 @@ import re
|
|
3 |
from http import HTTPStatus
|
4 |
from typing import Dict, List, Optional, Tuple
|
5 |
import base64
|
|
|
|
|
|
|
6 |
|
7 |
import gradio as gr
|
8 |
from huggingface_hub import InferenceClient
|
@@ -364,7 +367,31 @@ def demo_card_click(e: gr.EventData):
|
|
364 |
# Return the first demo description as fallback
|
365 |
return DEMO_LIST[0]['description']
|
366 |
|
367 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
368 |
if query is None:
|
369 |
query = ''
|
370 |
if _history is None:
|
@@ -374,6 +401,14 @@ def generation_code(query: Optional[str], image: Optional[gr.Image], _setting: D
|
|
374 |
system_prompt = SystemPromptWithSearch if enable_search else _setting['system']
|
375 |
messages = history_to_messages(_history, system_prompt)
|
376 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
377 |
# Enhance query with search if enabled
|
378 |
enhanced_query = enhance_query_with_search(query, enable_search)
|
379 |
|
@@ -431,6 +466,7 @@ with gr.Blocks(theme=gr.themes.Base(), title="AnyCoder - AI Code Generator") as
|
|
431 |
gr.Markdown("# AnyCoder\nAI-Powered Code Generator")
|
432 |
gr.Markdown("""Describe your app or UI in plain English. Optionally upload a UI image (for ERNIE model). Click Generate to get code and preview.""")
|
433 |
gr.Markdown("**Tip:** For best search results about people or entities, include details like profession, company, or location. Example: 'John Smith software engineer at Google.'")
|
|
|
434 |
input = gr.Textbox(
|
435 |
label="Describe your application",
|
436 |
placeholder="e.g., Create a todo app with add, delete, and mark as complete functionality",
|
@@ -440,6 +476,11 @@ with gr.Blocks(theme=gr.themes.Base(), title="AnyCoder - AI Code Generator") as
|
|
440 |
label="Upload UI design image (ERNIE-4.5-VL only)",
|
441 |
visible=False
|
442 |
)
|
|
|
|
|
|
|
|
|
|
|
443 |
with gr.Row():
|
444 |
btn = gr.Button("Generate", variant="primary", size="sm")
|
445 |
clear_btn = gr.Button("Clear", variant="secondary", size="sm")
|
@@ -517,10 +558,10 @@ with gr.Blocks(theme=gr.themes.Base(), title="AnyCoder - AI Code Generator") as
|
|
517 |
# Event handlers
|
518 |
btn.click(
|
519 |
generation_code,
|
520 |
-
inputs=[input, image_input, setting, history, current_model, search_toggle],
|
521 |
outputs=[code_output, history, sandbox, status_indicator, history_output]
|
522 |
)
|
523 |
-
clear_btn.click(clear_history, outputs=[history, history_output])
|
524 |
|
525 |
if __name__ == "__main__":
|
526 |
demo.queue(default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=True)
|
|
|
3 |
from http import HTTPStatus
|
4 |
from typing import Dict, List, Optional, Tuple
|
5 |
import base64
|
6 |
+
import mimetypes
|
7 |
+
import PyPDF2
|
8 |
+
import docx
|
9 |
|
10 |
import gradio as gr
|
11 |
from huggingface_hub import InferenceClient
|
|
|
367 |
# Return the first demo description as fallback
|
368 |
return DEMO_LIST[0]['description']
|
369 |
|
370 |
+
def extract_text_from_file(file_path):
|
371 |
+
if not file_path:
|
372 |
+
return ""
|
373 |
+
mime, _ = mimetypes.guess_type(file_path)
|
374 |
+
ext = os.path.splitext(file_path)[1].lower()
|
375 |
+
try:
|
376 |
+
if ext == ".pdf":
|
377 |
+
with open(file_path, "rb") as f:
|
378 |
+
reader = PyPDF2.PdfReader(f)
|
379 |
+
return "\n".join(page.extract_text() or "" for page in reader.pages)
|
380 |
+
elif ext in [".txt", ".md"]:
|
381 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
382 |
+
return f.read()
|
383 |
+
elif ext == ".csv":
|
384 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
385 |
+
return f.read()
|
386 |
+
elif ext == ".docx":
|
387 |
+
doc = docx.Document(file_path)
|
388 |
+
return "\n".join([para.text for para in doc.paragraphs])
|
389 |
+
else:
|
390 |
+
return ""
|
391 |
+
except Exception as e:
|
392 |
+
return f"Error extracting text: {e}"
|
393 |
+
|
394 |
+
def generation_code(query: Optional[str], image: Optional[gr.Image], file: Optional[str], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, enable_search: bool = False):
|
395 |
if query is None:
|
396 |
query = ''
|
397 |
if _history is None:
|
|
|
401 |
system_prompt = SystemPromptWithSearch if enable_search else _setting['system']
|
402 |
messages = history_to_messages(_history, system_prompt)
|
403 |
|
404 |
+
# Extract file text and append to query if file is present
|
405 |
+
file_text = ""
|
406 |
+
if file:
|
407 |
+
file_text = extract_text_from_file(file)
|
408 |
+
if file_text:
|
409 |
+
file_text = file_text[:5000] # Limit to 5000 chars for prompt size
|
410 |
+
query = f"{query}\n\n[Reference file content below]\n{file_text}"
|
411 |
+
|
412 |
# Enhance query with search if enabled
|
413 |
enhanced_query = enhance_query_with_search(query, enable_search)
|
414 |
|
|
|
466 |
gr.Markdown("# AnyCoder\nAI-Powered Code Generator")
|
467 |
gr.Markdown("""Describe your app or UI in plain English. Optionally upload a UI image (for ERNIE model). Click Generate to get code and preview.""")
|
468 |
gr.Markdown("**Tip:** For best search results about people or entities, include details like profession, company, or location. Example: 'John Smith software engineer at Google.'")
|
469 |
+
gr.Markdown("**Tip:** You can attach a file (PDF, TXT, DOCX, CSV, MD) to use as reference for your prompt, e.g. 'Summarize this PDF.'")
|
470 |
input = gr.Textbox(
|
471 |
label="Describe your application",
|
472 |
placeholder="e.g., Create a todo app with add, delete, and mark as complete functionality",
|
|
|
476 |
label="Upload UI design image (ERNIE-4.5-VL only)",
|
477 |
visible=False
|
478 |
)
|
479 |
+
file_input = gr.File(
|
480 |
+
label="Attach a file (PDF, TXT, DOCX, CSV, MD)",
|
481 |
+
file_types=[".pdf", ".txt", ".md", ".csv", ".docx"],
|
482 |
+
visible=True
|
483 |
+
)
|
484 |
with gr.Row():
|
485 |
btn = gr.Button("Generate", variant="primary", size="sm")
|
486 |
clear_btn = gr.Button("Clear", variant="secondary", size="sm")
|
|
|
558 |
# Event handlers
|
559 |
btn.click(
|
560 |
generation_code,
|
561 |
+
inputs=[input, image_input, file_input, setting, history, current_model, search_toggle],
|
562 |
outputs=[code_output, history, sandbox, status_indicator, history_output]
|
563 |
)
|
564 |
+
clear_btn.click(clear_history, outputs=[history, history_output, file_input])
|
565 |
|
566 |
if __name__ == "__main__":
|
567 |
demo.queue(default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=True)
|
requirements.txt
CHANGED
@@ -1,3 +1,5 @@
|
|
1 |
git+https://github.com/huggingface/huggingface_hub.git
|
2 |
gradio[oauth]
|
3 |
-
tavily-python
|
|
|
|
|
|
1 |
git+https://github.com/huggingface/huggingface_hub.git
|
2 |
gradio[oauth]
|
3 |
+
tavily-python
|
4 |
+
PyPDF2
|
5 |
+
python-docx
|