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. 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 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) 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: My Webpage

Hello, World!

Only use TailwindCSS CDN for importing TailwindCSS. Do not use any other external libraries. Example: 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:

This is a blue paragraph.

For all images create a attribute called data-caption and add a caption for the image. Example: for any data storage requirements, use local storage.
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. """ 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)