Spaces:
Running
Running
File size: 10,923 Bytes
1aa403a f7b4872 1aa403a f7b4872 1aa403a 801e088 1aa403a 801e088 1aa403a f7b4872 1aa403a f7b4872 1aa403a |
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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
from django.http import HttpResponse, JsonResponse
import requests
import json
import time
from django.views.decorators.csrf import csrf_exempt
from .models import Projects, Version
MODEL = 'claude-3.5-sonnet'
mainPrompt = """
You are Tailwind Expert, an AI assistant specializing in HTML and TailwindCSS development. You excel at creating responsive, modern web interfaces using TailwindCSS best practices and utility-first principles.
<system_constraints>
You are operating in an environment called WebContainer, an in-browser runtime that emulates a Browser to some degree. All code is executed in the browser.
Key limitations:
- No backend server capabilities
- No database connections
- Limited to client-side functionality
- Cannot execute native binaries
- No Git support
The environment supports:
- HTML, CSS, and JavaScript
- TailwindCSS
</system_constraints>
<code_formatting_info>
Use 2 spaces for indentation
Follow TailwindCSS class ordering conventions:
- Layout (container, display, position)
- Box Model (width, height, padding, margin)
- Visual (colors, backgrounds, borders)
- Typography (text, font)
- Other (transitions, transforms)
</code_formatting_info>
<code_structure_info>
All the code should be written in HTML, CSS, and JavaScript in single file and code block
Always use a single root element in your HTML structure. This is a requirement for proper rendering in the WebContainer environment.
Example:
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<div class="container mx-auto">
<h1 class="text-2xl font-bold text-center">Hello, World!</h1>
</div>
</body>
</html>
Only use TailwindCSS CDN for importing TailwindCSS. Do not use any other external libraries.
Example:
<script src="https://cdn.tailwindcss.com"></script>
Avoid inline styles and scripts. Use style tag for CSS and script tag for JavaScript instead if needed.
make sure to include the necessary TailwindCSS classes in your HTML elements to style them.
Example:
<p class="text-blue-500">This is a blue paragraph.</p>
For all images create a attribute called data-caption and add a caption for the image.
Example:
<img src="image.jpg" data-caption="This images includes a dog and cat">
for any data storage requirements, use local storage.
</code_structure_info>
<important_info>
Please note that the WebContainer environment is a sandboxed environment and does not have access to the internet. This means that you cannot fetch data from external APIs or websites. You can only use the data provided in the prompt or any data you generate within the environment.
Do not include anything in the ouput other that code and comments.
No need to explain the code, the code should be self explanatory.
No need of any extra conversation, just the code.
Do not worry about the length of the code, write the code as you would normally do.
Do not skip any steps, follow the instructions carefully.
</important_info>
"""
def setup():
resp = requests.post('https://github.com/login/device/code', headers={
'accept': 'application/json',
'editor-version': 'Neovim/0.6.1',
'editor-plugin-version': 'copilot.vim/1.16.0',
'content-type': 'application/json',
'user-agent': 'GithubCopilot/1.155.0',
'accept-encoding': 'gzip,deflate,br'
}, data='{"client_id":"Iv1.b507a08c87ecfe98","scope":"read:user"}')
# Parse the response json, isolating the device_code, user_code, and verification_uri
resp_json = resp.json()
device_code = resp_json.get('device_code')
user_code = resp_json.get('user_code')
verification_uri = resp_json.get('verification_uri')
# Print the user code and verification uri
print(f'Please visit {verification_uri} and enter code {user_code} to authenticate.')
while True:
time.sleep(5)
resp = requests.post('https://github.com/login/oauth/access_token', headers={
'accept': 'application/json',
'editor-version': 'Neovim/0.6.1',
'editor-plugin-version': 'copilot.vim/1.16.0',
'content-type': 'application/json',
'user-agent': 'GithubCopilot/1.155.0',
'accept-encoding': 'gzip,deflate,br'
}, data=f'{{"client_id":"Iv1.b507a08c87ecfe98","device_code":"{device_code}","grant_type":"urn:ietf:params:oauth:grant-type:device_code"}}')
# Parse the response json, isolating the access_token
resp_json = resp.json()
access_token = resp_json.get('access_token')
if access_token:
break
# Save the access token to a file
with open('.copilot_token', 'w') as f:
f.write(access_token)
print('Authentication success!')
def get_token():
global token
# Check if the .copilot_token file exists
while True:
try:
with open('.copilot_token', 'r') as f:
access_token = f.read()
break
except FileNotFoundError:
setup()
# Get a session with the access token
resp = requests.get('https://api.github.com/copilot_internal/v2/token', headers={
'authorization': f'token {access_token}',
'editor-version': 'Neovim/0.6.1',
'editor-plugin-version': 'copilot.vim/1.16.0',
'user-agent': 'GithubCopilot/1.155.0'
})
# Parse the response json, isolating the token
resp_json = resp.json()
token = resp_json.get('token')
get_token()
def chat(message):
get_token()
global token, mainPrompt
messages = []
messages.append({
"content": mainPrompt + "\n\n---\n" + str(message),
"role": "user"
})
try:
resp = requests.post('https://api.githubcopilot.com/chat/completions', headers={
'authorization': f'Bearer {token}',
'Editor-Version': 'vscode/1.80.1',
}, json={
'intent': False,
'model': MODEL,
'temperature': 0,
'top_p': 1,
'n': 1,
# 'stream': True,
'messages': messages
})
except requests.exceptions.ConnectionError:
return ''
try:
result = resp.json()["choices"][0]["message"]["content"]
if result == '':
print(resp.status_code)
print(resp.text)
return result
except Exception as e:
return str(e)
def index(request):
return HttpResponse("Hello, Moto")
@csrf_exempt
def builder(request):
if request.method == 'POST':
message = request.POST.get('message')
projectId = request.POST.get('projectId')
project = Projects.objects.filter(projectId=projectId).first()
try:
if project.currentVersion.generatedCode != "" and project.currentVersion.generatedCode is not None:
message = "This is my Previous Code:\n\n```\n"+project.currentVersion.generatedCode + "```\n\n" + message
except Exception as e:
print(e)
pass
response = chat(message)
data = {}
try:
response = response.replace("```html", "").replace("```", "")
newVersion = Version.objects.create(project=project, generatedCode=response, versionMessage=message)
newVersion.save()
project.currentVersion = newVersion
project.save()
data = {
"versionId": newVersion.versionId,
"versionMessage": newVersion.versionMessage,
"projectId": project.projectId,
"content": response,
"created_at": newVersion.created_at,
"updated_at": newVersion.updated_at,
}
except Exception as e:
print(e)
return JsonResponse({"html": response, "data": data})
else:
return HttpResponse("Invalid request method")
@csrf_exempt
def projectCreator(request):
if request.method == 'POST':
title = request.POST.get('title')
description = request.POST.get('description')
slug = request.POST.get('slug')
userEmail = request.POST.get('userEmail')
project = Projects.objects.create(title=title, description=description, slag=slug, userEmail=userEmail)
project.save()
initVersion = Version.objects.create(project=project, versionMessage="Initial version", generatedCode="")
initVersion.save()
project.currentVersion = initVersion
project.save()
data = {
"title": title,
"description": description,
"slag": slug,
"userEmail": userEmail,
"id": project.projectId,
"created_at": project.created_at,
"updated_at": project.updated_at,
"currentVersion": initVersion.versionId,
}
return JsonResponse(data)
else:
return HttpResponse("Invalid request method")
def projectList(request):
projects = Projects.objects.all()
data = []
for project in projects:
data.append({
"previewUrl": "/projects/deployed/"+project.projectId,
"imageUrl": project.projectScreenshot,
"customizeUrl": "/projects/"+project.projectId,
"title": project.title,
"description": project.description,
"slag": project.slag,
"userEmail": project.userEmail,
"id": project.projectId,
"created_at": project.created_at,
"updated_at": project.updated_at,
"currentVersion": project.currentVersion.versionId,
"currentCode": project.currentVersion.generatedCode,
})
return JsonResponse(data, safe=False)
def projectDetail(request, projectId):
project = Projects.objects.get(projectId=projectId)
data = {
"title": project.title,
"description": project.description,
"slag": project.slag,
"userEmail": project.userEmail,
"id": project.projectId,
"created_at": project.created_at,
"updated_at": project.updated_at,
"currentVersion": project.currentVersion.versionId,
"currentCode": project.currentVersion.generatedCode,
}
return JsonResponse(data)
def versionList(request, projectId):
project = Projects.objects.get(projectId=projectId)
versions = Version.objects.filter(project=project)
data = []
for version in versions:
data.append({
"versionId": version.versionId,
"versionMessage": version.versionMessage,
"created_at": version.created_at,
"updated_at": version.updated_at,
})
return JsonResponse(data, safe=False)
|