unicodeToSVGmain.tsx1 match
50return new Response(svgResponse, {
51headers: {
52'Content-Type': 'image/svg+xml',
53'Access-Control-Allow-Origin': '*'
54}
1import { Image } from "https://deno.land/x/imagescript@1.2.15/mod.ts";
23function encodeURL(url: string): string {
1011const {
12w, // Width of the output image
13h, // Height of the output image
14fit, // Fit mode for resizing: 'cover' or 'contain'
15background, // Background color for 'contain' mode or transparent areas
16withoutEnlargement, // Whether to prevent enlarging the image
17format = 'base64' // URL format: 'base64' or 'plain'
18} = Object.fromEntries(params);
2223if (!inputUrl) {
24const exampleUrl = "https://example.com/image.jpg";
25const encodedExampleUrl = encodeURL(exampleUrl);
26const baseUrl = `${url.protocol}//${url.host}/`;
27const exampleBase64 = `${baseUrl}${encodedExampleUrl}?format=base64`;
28const examplePlain = `${baseUrl}${exampleUrl}?format=plain`;
29return new Response(`Error: No image URL provided. Please include a URL in the path and specify the format using the 'format' parameter.
3031Example usage:
442. w (integer, optional):
45- Values: Any positive integer
46- Specifies the desired width of the output image in pixels
47- If omitted, the original image width is used
48- Example: w=300
49503. h (integer, optional):
51- Values: Any positive integer
52- Specifies the desired height of the output image in pixels
53- If omitted, the original image height is used
54- Example: h=200
55564. fit (string, optional):
57- Values: 'cover' (default) or 'contain'
58- Determines how the image should be resized to fit the specified dimensions
59- 'cover': The image will fill the specified dimensions while maintaining its aspect ratio, potentially cropping the image
60- 'contain': The image will be resized to fit within the specified dimensions while maintaining its aspect ratio, potentially adding letterboxing
61- Example: fit=contain
62696. withoutEnlargement (string, optional):
70- Values: 'true' or 'false' (default)
71- When set to 'true', prevents the image from being enlarged if the requested dimensions are larger than the original image
72- Example: withoutEnlargement=true
7374Usage notes:
75- The image URL should be provided in the path of the request URL
76- At least one of 'w' or 'h' should be provided to resize the image
77- If only one of 'w' or 'h' is provided, the other dimension will be calculated to maintain the aspect ratio
78- The 'background' parameter is only used when 'fit' is set to 'contain' or when the image has transparent areas
79- All parameters are optional. If not provided, default values or original image properties will be used`,
80{ status: 400 });
81}
8283let imageUrl;
84try {
85if (format === 'base64') {
86imageUrl = decodeURIComponent(atob(inputUrl));
87} else if (format === 'plain') {
88imageUrl = decodeURIComponent(inputUrl);
89} else {
90throw new Error('Invalid format specified. Use "base64" or "plain".');
91}
92console.log('Processed URL:', imageUrl);
93} catch (error) {
94return new Response(`Error processing URL: ${error.message}. Please ensure the URL is correctly formatted and the format is specified correctly.`, { status: 400 });
9697try {
98console.log('Fetching image from:', imageUrl);
99const response = await fetch(imageUrl);
100if (!response.ok) {
101throw new Error(`HTTP error! status: ${response.status}`);
103const arrayBuffer = await response.arrayBuffer();
104105let image = await Image.decode(new Uint8Array(arrayBuffer));
106107const targetWidth = w ? parseInt(w) : image.width;
108const targetHeight = h ? parseInt(h) : image.height;
109110if (withoutEnlargement === "true" && (targetWidth > image.width || targetHeight > image.height)) {
111// Don't enlarge the image
112} else {
113if (fit === "contain") {
114image = image.contain(targetWidth, targetHeight);
115} else {
116// Default to 'cover'
117image = image.cover(targetWidth, targetHeight);
118}
119}
121if (background) {
122try {
123const bgColor = Image.rgbaToColor(...JSON.parse(background));
124const bgImage = new Image(image.width, image.height);
125bgImage.fill(bgColor);
126image = bgImage.composite(image);
127} catch (error) {
128console.error('Error applying background:', error);
131}
132133const encodedImage = await image.encode();
134135return new Response(encodedImage, {
136status: 200,
137headers: {
138"Content-Type": "image/png",
139"Cache-Control": "max-age=86400"
140}
141});
142} catch (error) {
143console.error('Error processing image:', error);
144let errorMessage = `Error processing image: ${error.message}. `;
145if (error.message.includes('HTTP error')) {
146errorMessage += 'The image could not be fetched from the provided URL. Please check if the URL is correct and accessible.';
147} else if (error.message.includes('decode')) {
148errorMessage += 'The image could not be decoded. Please ensure the URL points to a valid image file.';
149} else if (error.message.includes('client error (Connect)')) {
150errorMessage += 'There was a network error while trying to fetch the image. This might be due to network restrictions or the image server being unreachable.';
151} else {
152errorMessage += 'An unexpected error occurred while processing the image. Please try again or contact support if the issue persists.';
153}
154return new Response(errorMessage, { status: 500 });
removeBackgroundPhotomain.tsx26 matches
45function BackgroundRemover() {
6const [image, setImage] = useState<string | null>(null);
7const [processedImage, setProcessedImage] = useState<string | null>(null);
8const canvasRef = useRef<HTMLCanvasElement>(null);
910const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
11const file = e.target.files?.[0];
12if (file) {
13const reader = new FileReader();
14reader.onload = (event) => {
15setImage(event.target?.result as string);
16};
17reader.readAsDataURL(file);
2021const removeBackground = () => {
22if (!canvasRef.current || !image) return;
2324const canvas = canvasRef.current;
25const ctx = canvas.getContext('2d');
26const img = new Image();
27img.onload = () => {
28canvas.width = img.width;
29canvas.height = img.height;
30ctx?.drawImage(img, 0, 0);
3132const imageData = ctx?.getImageData(0, 0, canvas.width, canvas.height);
33if (imageData) {
34for (let i = 0; i < imageData.data.length; i += 4) {
35// Simple background removal: make white/near-white pixels transparent
36const r = imageData.data[i];
37const g = imageData.data[i + 1];
38const b = imageData.data[i + 2];
39
40// If pixel is very close to white, make it transparent
41if (r > 240 && g > 240 && b > 240) {
42imageData.data[i + 3] = 0;
43}
44}
45ctx?.putImageData(imageData, 0, 0);
46setProcessedImage(canvas.toDataURL());
47}
48};
49img.src = image;
50};
5160<input
61type="file"
62accept="image/*"
63onChange={handleImageUpload}
64style={{ marginBottom: '10px' }}
65/>
66{image && (
67<div>
68<h2>Original Image</h2>
69<img
70src={image}
71alt="Original"
72style={{ maxWidth: '100%', maxHeight: '300px' }}
86</div>
87)}
88{processedImage && (
89<div>
90<h2>Processed Image</h2>
91<img
92src={processedImage}
93alt="Background Removed"
94style={{ maxWidth: '100%', maxHeight: '300px' }}
95/>
96<a
97href={processedImage}
98download="background-removed.png"
99style={{
ios_AppStoreFetchermain.tsx1 match
367368// Extract icon
369const iconUrlMatch = html.match(/<meta property="og:image" content="([^"]+)"/i);
370let iconUrl = iconUrlMatch ? iconUrlMatch[1] : null;
371
cerebras_codermain.tsx1 match
1191<meta property="og:description" content="Turn your ideas into fully functional apps in less than a second – powered by Llama3.3-70b on Cerebras's super-fast wafer chips. Code is 100% open-source, hosted on Val Town."">
1192<meta property="og:type" content="website">
1193<meta property="og:image" content="https://stevekrouse-blob_admin.web.val.run/api/public/CerebrasCoderOG.jpg">
1194
1195
blobStorageREADME.md1 match
3This is a lightweight Blob Admin interface to view and debug your Blob data.
45
67Versions 0-17 of this val were done with Hono and server-rendering.
blobStoragemain.tsx5 matches
440{profile && (
441<div className="flex items-center space-x-4">
442<img src={profile.profileImageUrl} alt="Profile" className="w-8 h-8 rounded-full" />
443<span>{profile.username}</span>
444<a href="/auth/logout" className="text-blue-400 hover:text-blue-300">Logout</a>
583alt="Blob content"
584className="max-w-full h-auto"
585onError={() => console.error("Error loading image")}
586/>
587</div>
635<li>Create public shareable links for blobs</li>
636<li>View and manage public folder</li>
637<li>Preview images directly in the interface</li>
638</ul>
639</div>
694const { ValTown } = await import("npm:@valtown/sdk");
695const vt = new ValTown();
696const { email: authorEmail, profileImageUrl, username } = await vt.me.profile.retrieve();
697// const authorEmail = me.email;
698762763c.set("email", email);
764c.set("profile", { profileImageUrl, username });
765await next();
766};
emailValHandlermain.tsx25 matches
11- Parse and analyze various types of content:
12- PDF attachments
13- Image attachments (using GPT-4 Vision)
14- Website content from links in your email
15- Get detailed, context-aware responses directly to your inbox
294. Compose your email:
30- Write your query or request in the email body
31- Attach any relevant PDFs or images
32- Include links to websites you want analyzed
33- Send it to the Val email address
4546- PDFs: Text content will be extracted and analyzed
47- Images: Will be analyzed using GPT-4 Vision API
48- Websites: Content will be extracted and converted to markdown for analysis
49- Other file types are not currently supported and will be ignored
7980// Step 3: Process different types of content
81const { pdfTexts, imageAnalysis } = await processAttachments(attachments, openaiKey, transformedPrompt);
82const websiteMarkdown = await extractWebsiteMarkdown(links, mdApiKey);
8386transformedPrompt,
87pdfTexts,
88imageAnalysis,
89websiteMarkdown,
90receivedEmail,
176}
177178// Process image attachments with GPT-4V
179async function analyzeImage(imageAttachment, apiKey, transformedPrompt) {
180try {
181const response = await fetch("https://api.openai.com/v1/chat/completions", {
191role: "system",
192content:
193`You are an AI assistant tasked with analyzing images in the context of a specific query. Use the following transformed prompt to guide your analysis and provide relevant context:\n\n${transformedPrompt}\n\nFocus your analysis on aspects that are most relevant to this prompt.`,
194},
195{
198{
199type: "text",
200text: "Analyze this image and provide relevant context based on the given prompt:${transformedPrompt}",
201},
202{
203type: "image_url",
204image_url: {
205url: `data:${imageAttachment.type};base64,${imageAttachment.content}`,
206},
207},
215return data.choices[0]?.message?.content || "No analysis available";
216} catch (error) {
217console.error("Error analyzing image:", error);
218return "Error analyzing image";
219}
220}
310}
311312// Process all attachments (PDFs and Images)
313async function processAttachments(attachments, apiKey, transformedPrompt) {
314const pdfTexts = [];
315const imageAnalysis = [];
316317for (const attachment of attachments) {
319const pdfText = await extractPdfText([attachment]);
320pdfTexts.push(...pdfText);
321} else if (attachment.type.startsWith("image/")) {
322const analysis = await analyzeImage(attachment, apiKey, transformedPrompt);
323imageAnalysis.push({
324filename: attachment.filename,
325analysis,
328}
329330return { pdfTexts, imageAnalysis };
331}
332365366// Generate the final prompt with all context
367function generateFinalPrompt(transformedPrompt, pdfTexts, imageAnalysis, websiteMarkdown, email) {
368let contextDump = [];
369373}
374375// Add image analysis
376if (imageAnalysis.length > 0) {
377contextDump.push("Image Analysis:", ...imageAnalysis.map(img => `${img.filename}: ${img.analysis}`));
378}
379401role: "system",
402content:
403`You are a helpful AI that replies to emails. Address the sender by their first name if provided, and sign off as 'AI Assistant' in a friendly and professional tone. Be concise and thorough in your analysis. As you're replying via email, use email syntax and not markdown. Analyze all provided content, including PDFs, images, and website content, in the context of the email request. Follow the structured format provided in the transformed prompt to organize your response. Here's the transformed prompt to guide your response:\n\n${transformedPrompt}`,
404},
405{
blob_adminREADME.md1 match
3This is a lightweight Blob Admin interface to view and debug your Blob data.
45
67Versions 0-17 of this val were done with Hono and server-rendering.
blob_adminmain.tsx5 matches
440{profile && (
441<div className="flex items-center space-x-4">
442<img src={profile.profileImageUrl} alt="Profile" className="w-8 h-8 rounded-full" />
443<span>{profile.username}</span>
444<a href="/auth/logout" className="text-blue-400 hover:text-blue-300">Logout</a>
583alt="Blob content"
584className="max-w-full h-auto"
585onError={() => console.error("Error loading image")}
586/>
587</div>
635<li>Create public shareable links for blobs</li>
636<li>View and manage public folder</li>
637<li>Preview images directly in the interface</li>
638</ul>
639</div>
694const { ValTown } = await import("npm:@valtown/sdk");
695const vt = new ValTown();
696const { email: authorEmail, profileImageUrl, username } = await vt.me.profile.retrieve();
697// const authorEmail = me.email;
698762763c.set("email", email);
764c.set("profile", { profileImageUrl, username });
765await next();
766};