add ernie vl support
Browse files92 unmodified lines9394959692 unmodified lines- **Hugging Face Hub**: For model inference- **ModelScope Studio**: For UI components- **OAuth Login**: Requires users to sign in with Hugging Face for code generation- **Streaming**: For real-time code generation92 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515692 unmodified lines- **Hugging Face Hub**: For model inference- **ModelScope Studio**: For UI components- **OAuth Login**: Requires users to sign in with Hugging Face for code generation- **Streaming**: For real-time code generation# Hugging Face CoderA Gradio-based application that uses Hugging Face models to generate code based on user requirements. The app supports both text-only and multimodal (text + image) code generation.## Features- **Multiple Model Support**: DeepSeek V3, DeepSeek R1, and ERNIE-4.5-VL- **Multimodal Input**: Upload images to help describe your requirements- **Real-time Code Generation**: Stream responses from the models- **Live Preview**: See your generated code in action with the built-in sandbox- **History Management**: Keep track of your previous generations- **Example Templates**: Quick-start with predefined application templates## Setup1. Install dependencies:```bashpip install -r requirements.txt```2. Set your Hugging Face API token as an environment variable:```bashexport HF_TOKEN="your_huggingface_token_here"```3. Run the application:```bashpython app.py```## Usage1. **Text-only Generation**: Simply type your requirements in the text area2. **Multimodal Generation**: Upload an image and describe what you want to create3. **Model Selection**: Switch between different models using the model selector4. **Examples**: Use the provided example templates to get started quickly## Supported Models- **DeepSeek V3**: General code generation- **DeepSeek R1**: Advanced code generation- **ERNIE-4.5-VL**: Multimodal code generation with image understanding## Environment Variables- `HF_TOKEN`: Your Hugging Face API token (required)## Examples- Todo App- Calculator- Weather Dashboard- Chat Interface- E-commerce Product Card- Login Form- Dashboard Layout- Data Table- Image Gallery- UI from Image (multimodal)
19 unmodified lines2021222324259 unmodified lines35363738394029 unmodified lines70717273747511 unmodified lines878889909192931 unmodified line959697989910010119 unmodified lines12112212312412512680 unmodified lines2072082092102112122 unmodified lines21521621721821922022163 unmodified lines2852862872882892908 unmodified lines2993003013023033043053063077 unmodified lines31531631731831932032136 unmodified lines3583593603613623633645 unmodified lines37037137237337437519 unmodified lines4. Include necessary comments and documentation5. Ensure the code is functional and follows best practicesAlways respond with code that can be executed or rendered directly.Always output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text."""9 unmodified lines"name": "DeepSeek R1","id": "deepseek-ai/DeepSeek-R1-0528","description": "DeepSeek R1 model for code generation"}]29 unmodified lines{"title": "Data Table","description": "Build a data table with sorting and filtering capabilities"}]11 unmodified linesdef history_to_messages(history: History, system: str) -> Messages:messages = [{'role': 'system', 'content': system}]for h in history:messages.append({'role': 'user', 'content': h[0]})messages.append({'role': 'assistant', 'content': h[1]})return messages1 unmodified lineassert messages[0]['role'] == 'system'history = []for q, r in zip(messages[1::2], messages[2::2]):history.append([q['content'], r['content']])return historydef remove_code_block(text):19 unmodified linesdef clear_history():return []def send_to_sandbox(code):# Add a wrapper to inject necessary permissions and ensure full HTMLwrapped_code = f"""80 unmodified linescurrent_model_display = gr.Markdown("**Current Model:** DeepSeek V3", visible=False)input = antd.InputTextarea(size="large", allow_clear=True, placeholder="Please enter what kind of application you want", visible=False)btn = antd.Button("send", type="primary", size="large", visible=False)clear_btn = antd.Button("clear history", type="default", size="large", visible=False)2 unmodified linesfor i, demo_item in enumerate(DEMO_LIST):with antd.Card(hoverable=True, title=demo_item["title"]) as demoCard:antd.CardMeta(description=demo_item["description"])demoCard.click(lambda e, idx=i: DEMO_LIST[idx]['description'], outputs=[input])antd.Divider("setting", visible=False)with antd.Flex(gap="small", wrap=True, visible=False) as setting_flex:63 unmodified linesgr.update(visible=False),gr.update(visible=False),gr.update(visible=False),)else:return (8 unmodified linesgr.update(visible=True),gr.update(visible=True),gr.update(visible=True),)def generation_code(query: Optional[str], _setting: Dict[str, str], _history: Optional[History], profile: gr.OAuthProfile | None, _current_model: Dict):if profile is None:return ("Please sign in with Hugging Face to use this feature.",7 unmodified linesif _history is None:_history = []messages = history_to_messages(_history, _setting['system'])messages.append({'role': 'user', 'content': query})try:completion = client.chat.completions.create(36 unmodified linesbtn.click(generation_code,inputs=[input, setting, history, current_model],outputs=[code_output, history, sandbox, state_tab, code_drawer])5 unmodified linesoutputs=[login_message,input,current_model_display,btn,clear_btn,19 unmodified lines20212223242526279 unmodified lines373839404142434445464729 unmodified lines777879808182838485868788899011 unmodified lines1021031041051061071081091101111121131141151161171181 unmodified line12012112212312412512612712812913013113213313413519 unmodified lines15515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920080 unmodified lines2812822832842852862872 unmodified lines29029129229329429529663 unmodified lines3603613623633643653668 unmodified lines3753763773783793803813823833847 unmodified lines39239339439539639739839940040140240336 unmodified lines4404414424434444454465 unmodified lines45245345445545645745819 unmodified lines4. Include necessary comments and documentation5. Ensure the code is functional and follows best practicesIf an image is provided, analyze it and use the visual information to better understand the user's requirements.Always respond with code that can be executed or rendered directly.Always output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text."""9 unmodified lines"name": "DeepSeek R1","id": "deepseek-ai/DeepSeek-R1-0528","description": "DeepSeek R1 model for code generation"},{"name": "ERNIE-4.5-VL","id": "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT","description": "ERNIE-4.5-VL model for multimodal code generation with image support"}]29 unmodified lines{"title": "Data Table","description": "Build a data table with sorting and filtering capabilities"},{"title": "Image Gallery","description": "Create an image gallery with lightbox functionality and responsive grid layout"},{"title": "UI from Image","description": "Upload an image of a UI design and I'll generate the HTML/CSS code for it"}]11 unmodified linesdef history_to_messages(history: History, system: str) -> Messages:messages = [{'role': 'system', 'content': system}]for h in history:# Handle multimodal content in historyuser_content = h[0]if isinstance(user_content, list):# Extract text from multimodal contenttext_content = ""for item in user_content:if isinstance(item, dict) and item.get("type") == "text":text_content += item.get("text", "")user_content = text_content if text_content else str(user_content)messages.append({'role': 'user', 'content': user_content})messages.append({'role': 'assistant', 'content': h[1]})return messages1 unmodified lineassert messages[0]['role'] == 'system'history = []for q, r in zip(messages[1::2], messages[2::2]):# Extract text content from multimodal messages for historyuser_content = q['content']if isinstance(user_content, list):text_content = ""for item in user_content:if isinstance(item, dict) and item.get("type") == "text":text_content += item.get("text", "")user_content = text_content if text_content else str(user_content)history.append([user_content, r['content']])return historydef remove_code_block(text):19 unmodified linesdef clear_history():return []def process_image_for_model(image):"""Convert image to base64 for model input"""if image is None:return None# Convert numpy array to PIL Image if neededimport ioimport base64import numpy as npfrom PIL import Image# Handle numpy array from Gradioif isinstance(image, np.ndarray):image = Image.fromarray(image)buffer = io.BytesIO()image.save(buffer, format='PNG')img_str = base64.b64encode(buffer.getvalue()).decode()return f"data:image/png;base64,{img_str}"def create_multimodal_message(text, image=None):"""Create a multimodal message with text and optional image"""if image is None:return {"role": "user", "content": text}content = [{"type": "text","text": text},{"type": "image_url","image_url": {"url": process_image_for_model(image)}}]return {"role": "user", "content": content}def send_to_sandbox(code):# Add a wrapper to inject necessary permissions and ensure full HTMLwrapped_code = f"""80 unmodified linescurrent_model_display = gr.Markdown("**Current Model:** DeepSeek V3", visible=False)input = antd.InputTextarea(size="large", allow_clear=True, placeholder="Please enter what kind of application you want", visible=False)image_input = gr.Image(label="Upload an image (optional)", visible=False)btn = antd.Button("send", type="primary", size="large", visible=False)clear_btn = antd.Button("clear history", type="default", size="large", visible=False)2 unmodified linesfor i, demo_item in enumerate(DEMO_LIST):with antd.Card(hoverable=True, title=demo_item["title"]) as demoCard:antd.CardMeta(description=demo_item["description"])demoCard.click(lambda e, idx=i: (DEMO_LIST[idx]['description'], None), outputs=[input, image_input])antd.Divider("setting", visible=False)with antd.Flex(gap="small", wrap=True, visible=False) as setting_flex:63 unmodified linesgr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),)else:return (8 unmodified linesgr.update(visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True),)def generation_code(query: Optional[str], image: Optional[gr.Image], _setting: Dict[str, str], _history: Optional[History], profile: gr.OAuthProfile | None, _current_model: Dict):if profile is None:return ("Please sign in with Hugging Face to use this feature.",7 unmodified linesif _history is None:_history = []messages = history_to_messages(_history, _setting['system'])# Create multimodal message if image is providedif image is not None:messages.append(create_multimodal_message(query, image))else:messages.append({'role': 'user', 'content': query})try:completion = client.chat.completions.create(36 unmodified linesbtn.click(generation_code,inputs=[input, image_input, setting, history, current_model],outputs=[code_output, history, sandbox, state_tab, code_drawer])5 unmodified linesoutputs=[login_message,input,image_input,current_model_display,btn,clear_btn,
README.md+61-1
app.py+89-6