remove ocr and auth message
Browse files3 unmodified lines4567891011121314155434 unmodified lines545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512353 unmodified lines5866586758685869587058715872587358745875587658773 unmodified lines5881588258835884588558865887588858895890589158925893589458955896188 unmodified lines6085608660876088608960906091609260936094609560966097717 unmodified lines681568166817681868196820682154 unmodified lines6876687768786879688068816882851 unmodified lines77347735773677377738773977407741774277437744774559 unmodified lines78057806780778087809781078117812781378147815580 unmodified lines839683978398839984008401840234 unmodified lines843784388439844084418442844327 unmodified lines8471847284738474847584768477643 unmodified lines91219122912391249125912691271 unmodified line91299130913191329133913491353 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 linesexcept (KeyError, IndexError, AttributeError) as e:# Return the first demo description as fallbackreturn DEMO_LIST[0]['description']def extract_text_from_image(image_path):"""Extract text from image using OCR"""try:# Check if tesseract is availabletry: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 OpenCVimage = 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 grayscalegray = 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 pytesseracttext = 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 linesreturn {# Enable main input and buttoninput: gr.update(interactive=True, placeholder="Describe your application..."),btn: gr.update(interactive=True, variant="primary"),# Show authentication statusauth_status: gr.update(value=f"✅ {auth_message}",visible=True)}else:# User not authenticated - disable main components3 unmodified linesinteractive=False,placeholder="🔒 Please log in with Hugging Face to use AnyCoder..."),btn: gr.update(interactive=False, variant="secondary"),# Show authentication requirementauth_status: gr.update(value=f"🔒 {auth_message}",visible=True)}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):# Check authentication firstis_authenticated, auth_message = check_authentication(profile, token)if not is_authenticated:188 unmodified linesmessages = history_to_messages(_history, system_prompt)# Extract file text and append to query if file is presentfile_text = ""if file:file_text = extract_text_from_file(file)if file_text:file_text = file_text[:5000] # Limit to 5000 chars for prompt sizequery = f"{query}\n\n[Reference file content below]\n{file_text}"# Extract website content and append to query if website URL is presentwebsite_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)- 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 mappingdependencies = set()special_cases = {'cv2': 'opencv-python','PIL': 'Pillow','sklearn': 'scikit-learn','skimage': 'scikit-image',851 unmodified lineswith gr.Sidebar() as sidebar:login_button = gr.LoginButton()# Authentication status displayauth_status = gr.Markdown(value="🔒 Please log in with your Hugging Face account to use AnyCoder.",visible=True,elem_classes=["auth-status"])59 unmodified lineslines=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 linesshow_progress="hidden",).then(generation_code,inputs=[input, image_input, file_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 linesshow_progress="hidden",).then(generation_code,inputs=[input, image_input, file_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 lineslanguage_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 changesspace_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(hide_deploy_components, None, [space_name_input, sdk_dropdown, deploy_btn])# Reset space name and button text when clearingclear_btn.click(643 unmodified lineslogin_button.click(handle_auth_update,inputs=[],outputs=[input, btn, auth_status],queue=False)1 unmodified linedemo.load(handle_auth_update,inputs=[],outputs=[input, btn, auth_status],queue=False)3 unmodified lines45678910115434 unmodified lines544654475448544954505451353 unmodified lines58055806580758085809581058113 unmodified lines58155816581758185819582058215822582358245825188 unmodified lines601460156016601760186019717 unmodified lines673767386739674067416742674354 unmodified lines679867996800680168026803851 unmodified lines76557656765776587659766059 unmodified lines772077217722772377247725580 unmodified lines830683078308830983108311831234 unmodified lines834783488349835083518352835327 unmodified lines8381838283838384838583868387643 unmodified lines90319032903390349035903690371 unmodified line90399040904190429043904490453 unmodified linesfrom typing import Dict, List, Optional, Tupleimport base64import mimetypesimport numpy as npfrom PIL import Imageimport requestsfrom urllib.parse import urlparse, urljoinfrom bs4 import BeautifulSoup5434 unmodified linesexcept (KeyError, IndexError, AttributeError) as e:# Return the first demo description as fallbackreturn DEMO_LIST[0]['description']def extract_website_content(url: str) -> str:"""Extract HTML code and content from a website URL"""353 unmodified linesreturn {# Enable main input and buttoninput: gr.update(interactive=True, placeholder="Describe your application..."),btn: gr.update(interactive=True, variant="primary")}else:# User not authenticated - disable main components3 unmodified linesinteractive=False,placeholder="🔒 Please log in with Hugging Face to use AnyCoder..."),btn: gr.update(interactive=False, variant="secondary")}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 firstis_authenticated, auth_message = check_authentication(profile, token)if not is_authenticated:188 unmodified linesmessages = history_to_messages(_history, system_prompt)# Extract website content and append to query if website URL is presentwebsite_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., 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 mappingdependencies = set()special_cases = {'PIL': 'Pillow','sklearn': 'scikit-learn','skimage': 'scikit-image',851 unmodified lineswith gr.Sidebar() as sidebar:login_button = gr.LoginButton()59 unmodified lineslines=1,visible=True)image_input = gr.Image(label="UI design image",visible=False580 unmodified linesshow_progress="hidden",).then(generation_code,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 linesshow_progress="hidden",).then(generation_code,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 lineslanguage_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 changesspace_name_input.change(update_deploy_button_text, inputs=[space_name_input], outputs=[deploy_btn])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 clearingclear_btn.click(643 unmodified lineslogin_button.click(handle_auth_update,inputs=[],outputs=[input, btn],queue=False)1 unmodified linedemo.load(handle_auth_update,inputs=[],outputs=[input, btn],queue=False)
app.py+9-99