-
-
Notifications
You must be signed in to change notification settings - Fork 247
import code in images (OCR) #837
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
7347299
feat(Import): allow importing code from images (OCR)
hatemhosny 79fa71f
edit code-to-image share url color
hatemhosny a0030c5
edit share url pattern
hatemhosny 694916f
search for share url in last 2 lines of image
hatemhosny bd8e549
remove line numbers after OCR
hatemhosny db91a27
Merge branch 'develop' into import-image
hatemhosny f79b013
fix removing line numbers
hatemhosny 58b2f26
feat(Code-to-Image): add share url to png meta data
hatemhosny cd056bb
feat(UI): show loading notification when importing from UI
hatemhosny b192195
handle svg as text
hatemhosny File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| import { detectLanguage, getLanguageByAlias, getLanguageEditorId, languages } from '../languages'; | ||
| import type { ContentConfig } from '../models'; | ||
| import { blobToBase64, loadScript } from '../utils/utils'; | ||
| import { metaPngUrl, tesseractUrl } from '../vendors'; | ||
| import { importCompressedCode } from './code'; | ||
| import { importProject } from './project-id'; | ||
|
|
||
| let Tesseract: | ||
| | { | ||
| createWorker: (lang: string) => Promise<{ | ||
| recognize: (blob: Blob) => Promise<{ data: { text: string } }>; | ||
| terminate: () => void; | ||
| }>; | ||
| } | ||
| | undefined; | ||
|
|
||
| const ocr = async (image: Blob) => { | ||
| Tesseract = Tesseract ?? (await import(tesseractUrl)).default; | ||
| if (!Tesseract) return ''; | ||
| const worker = await Tesseract.createWorker('eng'); | ||
| const ret = await worker.recognize(image); | ||
| worker.terminate(); | ||
| return ret.data.text; | ||
| }; | ||
|
|
||
| /** | ||
| * detect images created by LiveCodes "Code to Image" with share URL | ||
| */ | ||
| const getConfigFromShareUrl = (text: string, isShareUrl = false) => { | ||
| const shareUrlPattern = /\?x=(id\/\S{11,20})/g; | ||
| let projectId = [...text.matchAll(new RegExp(shareUrlPattern))].at(-1)?.[1]; | ||
| if (projectId) { | ||
| projectId = projectId.replace(/]/g, 'j'); | ||
| const alphabet = '23456789abcdefghijkmnpqrstuvwxyz'; | ||
| if ( | ||
| projectId | ||
| .slice('id/'.length) | ||
| .split('') | ||
| .every((c) => alphabet.includes(c)) | ||
| ) { | ||
| return importProject(projectId); | ||
| } | ||
| } | ||
| if (isShareUrl) { | ||
| try { | ||
| const url = new URL(text.trim()); | ||
| const code = decodeURIComponent(url.href.split('#config=')[1] || ''); | ||
| if (code) { | ||
| return importCompressedCode(code); | ||
| } | ||
| } catch { | ||
| // | ||
| } | ||
| } | ||
| return null; | ||
| }; | ||
|
|
||
| const cleanUpCode = async (code: string) => { | ||
| if (!code?.trim()) return ''; | ||
| let lines = code.trim().split('\n'); | ||
| const [firstLine, ...rest] = lines; | ||
| const lastLines = lines.slice(-2).join('\n'); | ||
|
|
||
| const config = await getConfigFromShareUrl(lastLines); | ||
| if (config) return config; | ||
|
|
||
| // remove first line if it contains window buttons | ||
| const buttonCharacters = ['0', 'C', 'N', 'J', 'X', '(', ')', '[', ']', '|']; | ||
| const charactersFound = firstLine | ||
| .slice(0, 6) | ||
| .split('') | ||
| .filter((c) => buttonCharacters.includes(c)).length; | ||
| const hasButtons = charactersFound > 2 || charactersFound / firstLine.length > 0.6; | ||
| if (hasButtons) { | ||
| code = rest.join('\n'); | ||
| } | ||
|
|
||
| lines = code.trim().split('\n'); | ||
|
|
||
| // remove line numbers | ||
| if (lines.filter((l) => l.match(/^[0-9]{1,4}\s?/)).length / lines.length > 0.3) { | ||
| code = lines.map((l) => l.replace(/^\S{1,4}\s?/, '')).join('\n'); | ||
| } | ||
|
|
||
| code = code.replace(/[ββ]/g, "'").replace(/[ββ]/g, '"'); | ||
| return code; | ||
| }; | ||
|
|
||
| export const importFromImage = async (blob: Blob): Promise<Partial<ContentConfig>> => { | ||
| try { | ||
| const metaPng: any = await loadScript(metaPngUrl, 'MetaPNG'); | ||
| const arrayBuffer = await blob.arrayBuffer(); | ||
| const uint8Array = new Uint8Array(arrayBuffer); | ||
| const livecodesUrl = metaPng.getMetadata(uint8Array, 'LiveCodes URL'); | ||
| if (livecodesUrl) { | ||
| const config = await getConfigFromShareUrl(livecodesUrl, true); | ||
| if (config) return config; | ||
| } | ||
| } catch { | ||
| // not PNG or not generated by LiveCodes, continue | ||
| } | ||
|
|
||
| try { | ||
| const text = await ocr(blob); | ||
| const content = await cleanUpCode(text); | ||
| if (content && typeof content === 'object') { | ||
| // config from share url | ||
| return content; | ||
| } | ||
|
|
||
| if (content.trim().length > 3) { | ||
| const langs = languages.map((lang) => lang.name); | ||
| const detected = await detectLanguage(content, langs); | ||
| detected.language = getLanguageByAlias(detected.language) || detected.language; | ||
| detected.secondBest = getLanguageByAlias(detected.secondBest) || detected.secondBest; | ||
| // language name or filename with extension in image | ||
| const langNamesInCode = languages | ||
| .filter( | ||
| (lang) => | ||
| content.search(new RegExp(`\\b${lang.name}\\b`, 'i')) !== -1 || | ||
| content.search(new RegExp(`\\b${lang.extensions[0]}\\b`, 'i')) !== -1, | ||
| ) | ||
| .map((lang) => lang.name); | ||
| const language = | ||
| langNamesInCode.find( | ||
| (lang) => lang === detected.language || lang === detected.secondBest, | ||
| ) ?? | ||
| langNamesInCode[0] ?? | ||
| detected.language ?? | ||
| detected.secondBest ?? | ||
| 'html'; | ||
|
|
||
| const editorId = getLanguageEditorId(language) ?? 'markup'; | ||
| return { | ||
| activeEditor: editorId, | ||
| [editorId]: { | ||
| language, | ||
| content, | ||
| }, | ||
| }; | ||
| } | ||
| } catch { | ||
| // | ||
| } | ||
|
|
||
| // fallback | ||
| return { | ||
| markup: { | ||
| language: 'html', | ||
| content: `<img src="${await blobToBase64(blob)}" alt="image" />`, | ||
| }, | ||
| }; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| import { shareService } from '../services'; | ||
|
|
||
| export const importProject = (url: string) => { | ||
| const id = url.slice(3); | ||
| const id = url.slice('id/'.length); | ||
| return shareService.getProject(id); | ||
| }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To make the detection more accurate, would it be beneficial to check for a base URL or similar prefix here?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure.
I want to support:
Do you have a better suggestion?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Anyway, this should be a lot less relevant after using png meta tags.