mgbam commited on
Commit
2f92e9e
·
verified ·
1 Parent(s): 9b171dd

Rename utils.py to deploy.py

Browse files
Files changed (2) hide show
  1. deploy.py +94 -0
  2. utils.py +0 -50
deploy.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def send_to_sandbox(code):
2
+ wrapped_code=f"""
3
+ <!DOCTYPE html>
4
+ <html>
5
+ <head>
6
+ <meta charset="UTF-8">
7
+ ...
8
+ </body>
9
+ </html>
10
+ """
11
+ encoded_html=base64.b64encode(wrapped_code.encode('utf-8')).decode('utf-8')
12
+ data_uri=f"data:text/html;charset=utf-8;base64,{encoded_html}"
13
+ return f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
14
+
15
+ def demo_card_click(e: gr.EventData):
16
+ ...
17
+ return DEMO_LIST[index]['description']
18
+
19
+ def wrap_html_in_gradio_app(html_code):
20
+ safe_html=html_code.replace('"""',r'\"\"\"')
21
+ return (
22
+ 'import gradio as gr\n\n'
23
+ 'def show_html():\n'
24
+ f' return """{safe_html}"""\n\n'
25
+ 'demo = gr.Interface(fn=show_html, inputs=None, outputs=gr.HTML())\n\n'
26
+ 'if __name__ == "__main__":\n'
27
+ ' demo.launch()\n'
28
+ )
29
+
30
+ def deploy_to_spaces(code):
31
+ if not code.strip(): return
32
+ app_py=wrap_html_in_gradio_app(code.strip())
33
+ ...
34
+ webbrowser.open_new_tab(full_url)
35
+
36
+ def wrap_html_in_static_app(html_code):
37
+ return html_code
38
+
39
+ def deploy_to_spaces_static(code):
40
+ if not code.strip(): return
41
+ app_html=wrap_html_in_static_app(code.strip())
42
+ ...
43
+ webbrowser.open_new_tab(full_url)
44
+
45
+ def check_hf_space_url(url: str) -> Tuple[bool, Optional[str], Optional[str]]:
46
+ import re
47
+ url_pattern=re.compile(
48
+ r'^(https?://)?(huggingface\.co|hf\.co)/spaces/([\w-]+)/([\w-]+)$',
49
+ re.IGNORECASE
50
+ )
51
+ match=url_pattern.match(url.strip())
52
+ if match:
53
+ return True, match.group(3), match.group(4)
54
+ return False, None, None
55
+
56
+ def fetch_hf_space_content(username: str, project_name: str) -> str:
57
+ try:
58
+ api=HfApi()
59
+ space_info=api.space_info(f"{username}/{project_name}")
60
+ sdk=space_info.sdk
61
+ ...
62
+ return f"""IMPORTED PROJECT FROM HUGGING FACE SPACE
63
+ ==============================================
64
+ Space: {username}/{project_name}
65
+ SDK: {sdk}
66
+ Main File: {main_file}
67
+ {file_content}"""
68
+ except Exception as e:
69
+ return f"Error fetching space content: {str(e)}"
70
+
71
+ def load_project_from_url(url: str) -> Tuple[str, str]:
72
+ is_valid,username,project_name=check_hf_space_url(url)
73
+ if not is_valid:
74
+ return "Error: Please enter a valid Hugging Face Spaces URL.\n\nExpected format: https://huggingface.co/spaces/username/project",""
75
+ content=fetch_hf_space_content(username,project_name)
76
+ if content.startswith("Error:"):
77
+ return content,""
78
+ lines=content.split('\n')
79
+ code_start=0
80
+ for i,line in enumerate(lines):
81
+ if line.strip() and not line.startswith(('=','IMPORTED','Space:','SDK:','Main File:')):
82
+ code_start=i
83
+ break
84
+ code_content='\n'.join(lines[code_start:])
85
+ return f"✅ Successfully imported project from {username}/{project_name}",code_content
86
+
87
+ def deploy_to_user_space(code, space_name, sdk_name, profile=None, token=None):
88
+ import shutil
89
+ if not code.strip():
90
+ return gr.update(value="No code to deploy.", visible=True)
91
+ if profile is None or token is None:
92
+ return gr.update(value="Please log in with your Hugging Face account to deploy to your own Space. Otherwise, use the default deploy (opens in new tab).", visible=True)
93
+ ...
94
+ return gr.update(value=f"✅ {action_text}! [Open your Space here]({space_url})", visible=True)
utils.py DELETED
@@ -1,50 +0,0 @@
1
- # /utils.py
2
- """ A collection of utility functions for data manipulation and formatting. """
3
- import base64, io, re, logging
4
- from typing import Dict, List, Optional, Tuple, Any
5
- import numpy as np
6
- from PIL import Image
7
- from config import SEARCH_START, DIVIDER, REPLACE_END, GRADIO_SUPPORTED_LANGUAGES
8
-
9
- History = List[Tuple[Optional[str], Optional[str]]]
10
- Messages = List[Dict[str, Any]]
11
-
12
- def history_to_messages(history: History, system_prompt: str) -> Messages:
13
- messages: Messages = [{'role': 'system', 'content': system_prompt}]
14
- for user_msg, assistant_msg in history:
15
- if user_msg: messages.append({'role': 'user', 'content': user_msg})
16
- if assistant_msg: messages.append({'role': 'assistant', 'content': assistant_msg})
17
- return messages
18
-
19
- def history_to_chatbot_messages(history: History) -> Messages:
20
- messages: Messages = []
21
- for user_msg, assistant_msg in history:
22
- display_text = ""
23
- if isinstance(user_msg, list): display_text = next((item.get("text", "") for item in user_msg if isinstance(item, dict) and item.get("type") == "text"), "")
24
- elif user_msg: display_text = user_msg
25
- if display_text: messages.append({"role": "user", "content": display_text})
26
- if assistant_msg: messages.append({"role": "assistant", "content": assistant_msg})
27
- return messages
28
-
29
- def process_image_for_model(image_data: np.ndarray) -> str:
30
- pil_img = Image.fromarray(image_data)
31
- buffer = io.BytesIO()
32
- pil_img.save(buffer, format="PNG")
33
- return f"data:image/png;base64,{base64.b64encode(buffer.getvalue()).decode('utf-8')}"
34
-
35
- def remove_code_block(text: str) -> str:
36
- pattern = r'```[a-zA-Z]*\s*\n?(.*?)\n?```'
37
- match = re.search(pattern, text, re.DOTALL)
38
- return match.group(1).strip() if match else text.strip()
39
-
40
- def apply_search_replace_changes(original_code: str, changes_text: str) -> str:
41
- modified_code = original_code
42
- block_pattern = re.compile(rf"^{SEARCH_START}\n(.*?)\n^{DIVIDER}\n(.*?)\n^{REPLACE_END}", re.DOTALL | re.MULTILINE)
43
- for match in block_pattern.finditer(changes_text):
44
- search_content, replace_content = match.groups()
45
- if search_content in modified_code: modified_code = modified_code.replace(search_content, replace_content, 1)
46
- else: logging.warning(f"Search block not found: {search_content[:100]}")
47
- return modified_code
48
-
49
- def get_gradio_language(language: str) -> Optional[str]:
50
- return language if language in GRADIO_SUPPORTED_LANGUAGES else None