remove ocr and auth message
Browse files3 unmodified lines4567897812910115434 unmodified lines544654475448545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509544954505451353 unmodified lines58055806580758695870587158725873587458085809581058113 unmodified lines581558165817588458855886588758885889581858195820582158935822582358245825188 unmodified lines6014601560166088608960906091609260936094601760186019717 unmodified lines6737673867396818674067416742674354 unmodified lines6798679968006879680168026803851 unmodified lines76557656765777377738773977407741774276587659766059 unmodified lines77207721772278087809781078117812772377247725580 unmodified lines8306830783088399830983108311831234 unmodified lines8347834883498440835083518352835327 unmodified lines83818382838384748384838583868387643 unmodified lines903190329033912490349035903690371 unmodified line903990409041913290429043904490453 unmodified linesfrom typing import Dict, List, Optional, Tupleimport base64import mimetypesimport PyPDF2import docximport cv2import numpy as npfrom PIL import Imageimport pytesseractimport requestsfrom urllib.parse import urlparse, urljoinfrom bs4 import BeautifulSoup5434 unmodified lines except (KeyError, IndexError, AttributeError) as e: # Return the first demo description as fallback return DEMO_LIST[0]['description']def extract_text_from_image(image_path): """Extract text from image using OCR""" try: # Check if tesseract is available try: pytesseract.get_tesseract_version() except Exception: return "Error: Tesseract OCR is not installed. Please install Tesseract to extract text from images. See install_tesseract.md for instructions." # Read image using OpenCV image = cv2.imread(image_path) if image is None: return "Error: Could not read image file" # Convert to RGB (OpenCV uses BGR) image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Preprocess image for better OCR results # Convert to grayscale gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY) # Apply thresholding to get binary image _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Extract text using pytesseract text = pytesseract.image_to_string(binary, config='--psm 6') return text.strip() if text.strip() else "No text found in image" except Exception as e: return f"Error extracting text from image: {e}"
def extract_text_from_file(file_path): if not file_path: return "" mime, _ = mimetypes.guess_type(file_path) ext = os.path.splitext(file_path)[1].lower() try: if ext == ".pdf": with open(file_path, "rb") as f: reader = PyPDF2.PdfReader(f) return "\n".join(page.extract_text() or "" for page in reader.pages) elif ext in [".txt", ".md"]: with open(file_path, "r", encoding="utf-8") as f: return f.read() elif ext == ".csv": with open(file_path, "r", encoding="utf-8") as f: return f.read() elif ext == ".docx": doc = docx.Document(file_path) return "\n".join([para.text for para in doc.paragraphs]) elif ext.lower() in [".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".gif", ".webp"]: return extract_text_from_image(file_path) else: return "" except Exception as e: return f"Error extracting text: {e}"
def extract_website_content(url: str) -> str: """Extract HTML code and content from a website URL"""353 unmodified lines return { # Enable main input and button input: gr.update(interactive=True, placeholder="Describe your application..."), btn: gr.update(interactive=True, variant="primary"), # Show authentication status auth_status: gr.update( value=f"β
{auth_message}", visible=True ) btn: gr.update(interactive=True, variant="primary") } else: # User not authenticated - disable main components3 unmodified lines interactive=False, placeholder="π Please log in with Hugging Face to use AnyCoder..." ), btn: gr.update(interactive=False, variant="secondary"), # Show authentication requirement auth_status: gr.update( value=f"π {auth_message}", visible=True ) btn: gr.update(interactive=False, variant="secondary") }
def generation_code(query: str | None, vlm_image: Optional[gr.Image], file: str | None, website_url: str | None, _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, language: str = "html", provider: str = "auto", profile: gr.OAuthProfile | None = None, token: gr.OAuthToken | None = None):def generation_code(query: str | None, vlm_image: Optional[gr.Image], website_url: str | None, _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, language: str = "html", provider: str = "auto", profile: gr.OAuthProfile | None = None, token: gr.OAuthToken | None = None): # Check authentication first is_authenticated, auth_message = check_authentication(profile, token) if not is_authenticated:188 unmodified lines
messages = history_to_messages(_history, system_prompt)
# Extract file text and append to query if file is present file_text = "" if file: file_text = extract_text_from_file(file) if file_text: file_text = file_text[:5000] # Limit to 5000 chars for prompt size query = f"{query}\n\n[Reference file content below]\n{file_text}"
# Extract website content and append to query if website URL is present website_text = ""717 unmodified linesInstructions:- Include the direct packages needed for the imports- Include commonly used companion packages and dependencies for better functionality- Use correct PyPI package names (e.g., cv2 -> opencv-python, PIL -> Pillow, sklearn -> scikit-learn)- Use correct PyPI package names (e.g., PIL -> Pillow, sklearn -> scikit-learn)- IMPORTANT: For diffusers, ALWAYS use: git+https://github.com/huggingface/diffusers- IMPORTANT: For transformers, ALWAYS use: git+https://github.com/huggingface/transformers- IMPORTANT: If diffusers is installed, also include transformers and sentencepiece as they usually go together54 unmodified lines # Fallback: simple extraction with basic mapping dependencies = set() special_cases = { 'cv2': 'opencv-python', 'PIL': 'Pillow', 'sklearn': 'scikit-learn', 'skimage': 'scikit-image',851 unmodified lines with gr.Sidebar() as sidebar: login_button = gr.LoginButton() # Authentication status display auth_status = gr.Markdown( value="π Please log in with your Hugging Face account to use AnyCoder.", visible=True, elem_classes=["auth-status"] )
59 unmodified lines lines=1, visible=True ) file_input = gr.File( label="Reference file (OCR only)", file_types=[".pdf", ".txt", ".md", ".csv", ".docx", ".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".gif", ".webp"], visible=True ) image_input = gr.Image( label="UI design image", visible=False580 unmodified lines show_progress="hidden", ).then( generation_code, inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, language_dropdown, provider_state], inputs=[input, image_input, website_url_input, setting, history, current_model, language_dropdown, provider_state], outputs=[code_output, history, sandbox, history_output] ).then( end_generation_ui,34 unmodified lines show_progress="hidden", ).then( generation_code, inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, language_dropdown, provider_state], inputs=[input, image_input, website_url_input, setting, history, current_model, language_dropdown, provider_state], outputs=[code_output, history, sandbox, history_output] ).then( end_generation_ui,27 unmodified lines language_dropdown.change(preview_logic, inputs=[code_output, language_dropdown, tjs_html_code, tjs_js_code, tjs_css_code], outputs=sandbox) # Update deploy button text when space name changes space_name_input.change(update_deploy_button_text, inputs=[space_name_input], outputs=[deploy_btn]) clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input]) clear_btn.click(clear_history, outputs=[history, history_output, website_url_input]) clear_btn.click(hide_deploy_components, None, [space_name_input, sdk_dropdown, deploy_btn]) # Reset space name and button text when clearing clear_btn.click(643 unmodified lines login_button.click( handle_auth_update, inputs=[], outputs=[input, btn, auth_status], outputs=[input, btn], queue=False ) 1 unmodified line demo.load( handle_auth_update, inputs=[], outputs=[input, btn, auth_status], outputs=[input, btn], queue=False )
app.py+9-99