Spaces:
Running
Running
File size: 6,719 Bytes
8207555 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
#!/usr/bin/env python3
"""Test script to validate zip generation functionality"""
import json
import zipfile
import io
import os
from datetime import datetime
def create_requirements():
"""Generate requirements.txt"""
return "gradio==4.16.0\nrequests==2.31.0"
def create_readme(config):
"""Generate README with deployment instructions"""
return f"""# {config['name']}
{config['description']}
## π Quick Deploy to HuggingFace Spaces
### Step 1: Create the Space
1. Go to https://huggingface.co/spaces
2. Click "Create new Space"
3. Choose a name for your assistant
4. Select **Gradio** as the SDK
5. Set visibility (Public/Private)
6. Click "Create Space"
### Step 2: Upload Files
1. In your new Space, click "Files" tab
2. Upload these files from the zip:
- `app.py`
- `requirements.txt`
3. Wait for "Building" to complete
### Step 3: Add API Key
1. Go to Settings (βοΈ icon)
2. Click "Variables and secrets"
3. Click "New secret"
4. Name: `{config['api_key_var']}`
5. Value: Your OpenRouter API key
6. Click "Add"
### Step 4: Get Your API Key
1. Go to https://openrouter.ai/keys
2. Sign up/login if needed
3. Click "Create Key"
4. Copy the key (starts with `sk-or-`)
### Step 5: Test Your Assistant
- Go back to "App" tab
- Your assistant should be running!
- Try the example prompts or ask a question
## π Configuration
- **Model**: {config['model']}
- **Temperature**: {config['temperature']}
- **Max Tokens**: {config['max_tokens']}
- **API Key Variable**: {config['api_key_var']}
Generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} with HF Assistant Converter
"""
# Fixed template based on mvp_simple.py
ASSISTANT_TEMPLATE = '''import gradio as gr
import os
import requests
import json
# Configuration
ASSISTANT_NAME = "{name}"
ASSISTANT_DESCRIPTION = "{description}"
SYSTEM_PROMPT = """{system_prompt}"""
MODEL = "{model}"
# Get API key from environment - customizable variable name
API_KEY = os.environ.get("{api_key_var}")
def generate_response(message, history):
"""Generate response using OpenRouter API"""
if not API_KEY:
return "Please set your {api_key_var} in the Space settings."
# Build messages array for the API
messages = [{{"role": "system", "content": SYSTEM_PROMPT}}]
# Add conversation history
for user_msg, assistant_msg in history:
messages.append({{"role": "user", "content": user_msg}})
if assistant_msg:
messages.append({{"role": "assistant", "content": assistant_msg}})
# Add current message
messages.append({{"role": "user", "content": message}})
# Make API request
try:
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={{
"Authorization": f"Bearer {{API_KEY}}",
"Content-Type": "application/json"
}},
json={{
"model": MODEL,
"messages": messages,
"temperature": {temperature},
"max_tokens": {max_tokens}
}}
)
if response.status_code == 200:
return response.json()['choices'][0]['message']['content']
else:
return f"Error: {{response.status_code}} - {{response.text}}"
except Exception as e:
return f"Error: {{str(e)}}"
# Create simple Gradio interface using ChatInterface
demo = gr.ChatInterface(
fn=generate_response,
title=ASSISTANT_NAME,
description=ASSISTANT_DESCRIPTION,
examples={examples}
)
if __name__ == "__main__":
demo.launch(share=True)
'''
def test_zip_generation():
"""Test the zip generation with sample data"""
print("π§ͺ Testing zip generation...")
# Sample configuration
config = {
'name': 'Test Assistant',
'description': 'A helpful test assistant',
'system_prompt': 'You are a helpful assistant. Provide clear and accurate responses.',
'model': 'google/gemma-2-9b-it',
'api_key_var': 'OPENROUTER_API_KEY',
'temperature': 0.7,
'max_tokens': 1024,
'examples': json.dumps([
"Hello! How can you help me?",
"Tell me something interesting",
"What can you do?"
])
}
print(f"π Config: {config}")
try:
# Generate files
print("π Generating app.py content...")
app_content = ASSISTANT_TEMPLATE.format(**config)
print("β
App content generated")
print("π Generating README content...")
readme_content = create_readme(config)
print("β
README content generated")
print("π Generating requirements content...")
requirements_content = create_requirements()
print("β
Requirements content generated")
# Create zip file
print("π Creating zip file...")
import time
timestamp = int(time.time())
filename = f"test_assistant_{timestamp}.zip"
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
zip_file.writestr('app.py', app_content)
zip_file.writestr('requirements.txt', requirements_content)
zip_file.writestr('README.md', readme_content)
zip_file.writestr('config.json', json.dumps(config, indent=2))
# Write to file
zip_buffer.seek(0)
with open(filename, 'wb') as f:
f.write(zip_buffer.getvalue())
# Verify file
if os.path.exists(filename):
file_size = os.path.getsize(filename)
print(f"β
Zip file created: {filename} ({file_size} bytes)")
# Test zip contents
with zipfile.ZipFile(filename, 'r') as zip_file:
files_in_zip = zip_file.namelist()
print(f"π Files in zip: {files_in_zip}")
# Test app.py content
app_py_content = zip_file.read('app.py').decode('utf-8')
print(f"π app.py first 100 chars: {app_py_content[:100]}...")
return True, filename
else:
print("β Zip file not created")
return False, None
except Exception as e:
print(f"β Error during zip generation: {str(e)}")
import traceback
traceback.print_exc()
return False, None
if __name__ == "__main__":
success, filename = test_zip_generation()
if success:
print(f"π Test successful! Generated: {filename}")
else:
print("π₯ Test failed!") |