[
  {
    "path": ".gitignore",
    "content": "venv\n.vscode\n.DS_Store\n.pyc\nnode_modules\n__pycache__\nserver/*.png\nserver/*.jpg\n*.psd"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2020 Cyril Diagne\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# AR Cut & Paste\n\nAn AR+ML prototype that allows cutting elements from your surroundings and pasting them in an image editing software.\n\nAlthough only Photoshop is being handled currently, it may handle different outputs in the future.\n\nDemo & more infos: [Thread](https://twitter.com/cyrildiagne/status/1256916982764646402)\n\n⚠️ This is a research prototype and not a consumer / photoshop user tool.\n\n**Update 2020.05.11:** If you're looking for an easy to use app based on this research, head over to https://clipdrop.co\n\n## Modules\n\nThis prototype runs as 3 independent modules:\n\n- **The mobile app**\n\n  - Check out the [/app](/app) folder for instructions on how to deploy the app to your mobile.\n\n- **The local server**\n\n  - The interface between the mobile app and Photoshop.\n  - It finds the position pointed on screen by the camera using [screenpoint](https://github.com/cyrildiagne/screenpoint)\n  - Check out the [/server](/server) folder for instructions on configuring the local server\n\n- **The object detection / background removal service**\n\n  - For now, the salience detection and background removal are delegated to an external service\n  - It would be a lot simpler to use something like [DeepLap](https://github.com/shaqian/tflite-react-native) directly within the mobile app. But that hasn't been implemented in this repo yet.\n\n## Usage\n\n### 1 - Configure Photoshop\n\n- Go to \"Preferences > Plug-ins\", enable \"Remote Connection\" and set a friendly password that you'll need later.\n- Make sure that your PS document settings match those in ```server/src/ps.py```, otherwise only an empty layer will be pasted.\n- Also make sure that your document has some sort of background. If the background is just blank, SIFT will probably not have enough feature to do a correct match.\n\n<!--\n### 2) Setup the local server\n\n```bash\nvirtualenv venv\nsource venv/bin/activate\npip install -r requirements.txt\n``` -->\n\n### 2 - Setup the external salience object detection service\n\n#### Option 1: Set up your own model service (requires a CUDA GPU)\n\n- As mentioned above, for the time being, you must deploy the\nBASNet model (Qin & al, CVPR 2019) as an external HTTP service using this [BASNet-HTTP wrapper](https://github.com/cyrildiagne/basnet-http) (requires a CUDA GPU)\n\n- You will need the deployed service URL to configure the local server\n\n- Make sure to configure a different port if you're running BASNet on the same computer as the local service\n\n#### Option 2: Use a community provided endpoint\n\nA public endpoint has been provided by members of the community. This is useful if you don't have your own CUDA GPU or do not want to go through the process of running the servce on your own.\n\nUse this endpoint by launching the local server with `--basnet_service_ip http://u2net-predictor.tenant-compass.global.coreweave.com`\n\n### 3 - Configure and run the local server\n\n- Follow the instructions in [/server](/server) to setup & run the local server.\n\n### 4 - Configure and run the mobile app\n\n- Follow the instructions in [/app](/app) to setup & deploy the mobile app.\n\n## Thanks and Acknowledgements\n\n- [BASNet code](https://github.com/NathanUA/BASNet) for '[*BASNet: Boundary-Aware Salient Object Detection*](http://openaccess.thecvf.com/content_CVPR_2019/html/Qin_BASNet_Boundary-Aware_Salient_Object_Detection_CVPR_2019_paper.html) [code](https://github.com/NathanUA/BASNet)', [Xuebin Qin](https://webdocs.cs.ualberta.ca/~xuebin/), [Zichen Zhang](https://webdocs.cs.ualberta.ca/~zichen2/), [Chenyang Huang](https://chenyangh.com/), [Chao Gao](https://cgao3.github.io/), [Masood Dehghan](https://sites.google.com/view/masoodd) and [Martin Jagersand](https://webdocs.cs.ualberta.ca/~jag/)\n- RunwayML for the [Photoshop paste code](https://github.com/runwayml/RunwayML-for-Photoshop/blob/master/host/index.jsx)\n- [CoreWeave](https://www.coreweave.com) for hosting the public U^2Net model endpoint on Tesla V100s\n"
  },
  {
    "path": "app/.expo-shared/assets.json",
    "content": "{\n  \"12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb\": true,\n  \"40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd\": true\n}\n"
  },
  {
    "path": "app/.gitignore",
    "content": "node_modules/**/*\n.expo/*\nnpm-debug.*\n*.jks\n*.p8\n*.p12\n*.key\n*.mobileprovision\n*.orig.*\nweb-build/\nweb-report/\n\n# macOS\n.DS_Store\n"
  },
  {
    "path": "app/App.tsx",
    "content": "import React, { useState, useEffect } from \"react\";\nimport {\n  Text,\n  View,\n  Image,\n  TouchableWithoutFeedback,\n  StyleSheet,\n} from \"react-native\";\nimport * as ImageManipulator from \"expo-image-manipulator\";\nimport { Camera } from \"expo-camera\";\n\nimport ProgressIndicator from \"./components/ProgressIndicator\";\nimport server from \"./components/Server\";\n\nconst styles = StyleSheet.create({\n  resultImgView: {\n    position: \"absolute\",\n    zIndex: 200,\n    top: 0,\n    left: 0,\n    width: \"100%\",\n    height: \"100%\",\n  },\n  resultImg: {\n    position: \"absolute\",\n    zIndex: 300,\n    top: \"25%\",\n    left: 0,\n    width: \"100%\",\n    height: \"50%\",\n  },\n});\n\ninterface State {\n  hasPermission: boolean;\n  type: any;\n  camera: any;\n  currImgSrc: string | null;\n}\n\nexport default function App() {\n  const [state, setState] = useState({\n    hasPermission: false,\n    type: Camera.Constants.Type.back,\n    camera: null,\n    currImgSrc: \"\",\n  } as State);\n\n  const [pressed, setPressed] = useState(false);\n  const [pasting, setPasting] = useState(false);\n\n  let camera: any = null;\n\n  useEffect(() => {\n    (async () => {\n      // Ping the server on startup.\n      server.ping();\n      // Request permission.\n      const { status } = await Camera.requestPermissionsAsync();\n      const hasPermission = status === \"granted\" ? true : false;\n      setState({ ...state, hasPermission });\n    })();\n  }, []);\n\n  async function cut(): Promise<string> {\n    const start = Date.now();\n    console.log(\"\");\n    console.log(\"Cut\");\n\n    console.log(camera.pictureSize);\n    // const ratios = await camera.getSupportedRatiosAsync()\n    // console.log(ratios)\n    // const sizes = await camera.getAvailablePictureSizeAsync(\"2:1\")\n    // console.log(sizes)\n\n    console.log(\"> taking image...\");\n    const opts = { skipProcessing: true, exif: false, quality: 0 };\n    // const opts = {};\n    let photo = await camera.takePictureAsync(opts);\n\n    console.log(\"> resizing...\");\n    const { uri } = await ImageManipulator.manipulateAsync(\n      photo.uri,\n      [\n        { resize: { width: 256, height: 512 } },\n        { crop: { originX: 0, originY: 128, width: 256, height: 256 } },\n        // { resize: { width: 256, height: 457 } },\n        // { crop: { originX: 0, originY: 99, width: 256, height: 256 } },\n        // { resize: { width: 256, height: 341 } },\n        // { crop: { originX: 0, originY: 42, width: 256, height: 256 } },\n      ]\n      // { compress: 0, format: ImageManipulator.SaveFormat.JPEG, base64: false }\n    );\n\n    console.log(\"> sending to /cut...\");\n    const resp = await server.cut(uri);\n\n    console.log(`Done in ${((Date.now() - start) / 1000).toFixed(3)}s`);\n    return resp;\n  }\n\n  async function paste() {\n    const start = Date.now();\n    console.log(\"\");\n    console.log(\"Paste\");\n\n    console.log(\"> taking image...\");\n    // const opts = { skipProcessing: true, exif: false };\n    const opts = {};\n    let photo = await camera.takePictureAsync(opts);\n\n    console.log(\"> resizing...\");\n    const { uri } = await ImageManipulator.manipulateAsync(photo.uri, [\n      // { resize: { width: 512, height: 1024 } },\n      { resize: { width: 350, height: 700 } },\n    ]);\n\n    console.log(\"> sending to /paste...\");\n    try {\n      const resp = await server.paste(uri);\n      if (resp.status !== \"ok\") {\n        if (resp.status === \"screen not found\") {\n          console.log(\"screen not found\");\n        } else {\n          throw new Error(resp);\n        }\n      }\n    } catch (e) {\n      console.error(\"error pasting:\", e);\n    }\n\n    console.log(`Done in ${((Date.now() - start) / 1000).toFixed(3)}s`);\n  }\n\n  async function onPressIn() {\n    setPressed(true);\n\n    const resp = await cut();\n\n    // Check if we're still pressed.\n    // if (pressed) {\n    setState({ ...state, currImgSrc: resp });\n    // }\n  }\n\n  async function onPressOut() {\n    setPressed(false);\n    setPasting(true);\n\n    if (state.currImgSrc !== \"\") {\n      await paste();\n      setState({ ...state, currImgSrc: \"\" });\n      setPasting(false);\n    }\n  }\n\n  if (state.hasPermission === null) {\n    return <View />;\n  }\n  if (state.hasPermission === false) {\n    return <Text>No access to camera</Text>;\n  }\n\n  let camOpacity = 1;\n  if (pressed && state.currImgSrc !== \"\") {\n    camOpacity = 0.8;\n  }\n\n  return (\n    <View style={{ flex: 1 }}>\n      <View\n        style={{ ...StyleSheet.absoluteFillObject, backgroundColor: \"black\" }}\n      ></View>\n      <Camera\n        style={{ flex: 1, opacity: camOpacity }}\n        type={state.type}\n        ratio=\"2:1\"\n        // autoFocus={false}\n        // pictureSize=\"640x480\"\n        ref={async (ref) => (camera = ref)}\n      >\n        <TouchableWithoutFeedback onPressIn={onPressIn} onPressOut={onPressOut}>\n          <View\n            style={{\n              flex: 1,\n              backgroundColor: \"transparent\",\n              flexDirection: \"row\",\n            }}\n          ></View>\n        </TouchableWithoutFeedback>\n      </Camera>\n\n      {pressed && state.currImgSrc !== \"\" ? (\n        <>\n          <View pointerEvents=\"none\" style={styles.resultImgView}>\n            <Image\n              style={styles.resultImg}\n              source={{ uri: state.currImgSrc }}\n              resizeMode=\"stretch\"\n            />\n          </View>\n        </>\n      ) : null}\n\n      {(pressed && state.currImgSrc === \"\") || pasting ? <ProgressIndicator /> : null}\n    </View>\n  );\n}\n"
  },
  {
    "path": "app/README.md",
    "content": "# AR Cut Paste Mobile App\n\nAn [Expo](expo.io) / [React Native](#) mobile application.\nPlease follow instructions from the [expo website](https://expo.io/learn) to see how to preview the app on your phone using the Expo app.\n\n## Setup\n\n```bash\nnpm install\n```\n\nThen update the IP address in `components/Server.tsx` to point to the IP address of the computer running the local server:\n```js\n3: const URL = \"http://192.168.1.29:8080\";\n```\n\n## Run\n\n```bash\nnpm start\n```\n"
  },
  {
    "path": "app/app.json",
    "content": "{\n  \"expo\": {\n    \"name\": \"app\",\n    \"slug\": \"app\",\n    \"platforms\": [\n      \"ios\",\n      \"android\",\n      \"web\"\n    ],\n    \"version\": \"1.0.0\",\n    \"orientation\": \"portrait\",\n    \"icon\": \"./assets/icon.png\",\n    \"splash\": {\n      \"image\": \"./assets/splash.png\",\n      \"resizeMode\": \"contain\",\n      \"backgroundColor\": \"#ffffff\"\n    },\n    \"updates\": {\n      \"fallbackToCacheTimeout\": 0\n    },\n    \"assetBundlePatterns\": [\n      \"**/*\"\n    ],\n    \"ios\": {\n      \"supportsTablet\": true\n    }\n  }\n}\n"
  },
  {
    "path": "app/babel.config.js",
    "content": "module.exports = function(api) {\n  api.cache(true);\n  return {\n    presets: ['babel-preset-expo'],\n  };\n};\n"
  },
  {
    "path": "app/components/Base64.tsx",
    "content": "// https://stackoverflow.com/questions/42829838/react-native-atob-btoa-not-working-without-remote-js-debugging\nconst chars =\n  \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\nconst Base64 = {\n  btoa: (input: string = \"\") => {\n    let str = input;\n    let output = \"\";\n\n    for (\n      let block = 0, charCode, i = 0, map = chars;\n      str.charAt(i | 0) || ((map = \"=\"), i % 1);\n      output += map.charAt(63 & (block >> (8 - (i % 1) * 8)))\n    ) {\n      charCode = str.charCodeAt((i += 3 / 4));\n\n      if (charCode > 0xff) {\n        throw new Error(\n          \"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\"\n        );\n      }\n\n      block = (block << 8) | charCode;\n    }\n\n    return output;\n  },\n\n  atob: (input: string = \"\") => {\n    let str = input.replace(/=+$/, \"\");\n    let output = \"\";\n\n    if (str.length % 4 == 1) {\n      throw new Error(\n        \"'atob' failed: The string to be decoded is not correctly encoded.\"\n      );\n    }\n    for (\n      let bc = 0, bs = 0, buffer, i = 0;\n      (buffer = str.charAt(i++));\n      ~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n        ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n        : 0\n    ) {\n      buffer = chars.indexOf(buffer);\n    }\n\n    return output;\n  },\n};\n\nFileReader.prototype.readAsArrayBuffer = function (blob) {\n  if (this.readyState === this.LOADING) throw new Error(\"InvalidStateError\");\n  this._setReadyState(this.LOADING);\n  this._result = null;\n  this._error = null;\n  const fr = new FileReader();\n  fr.onloadend = () => {\n    const content = Base64.atob(\n      fr.result.substr(fr.result.indexOf(',') + 1)\n    );\n    const buffer = new ArrayBuffer(content.length);\n    const view = new Uint8Array(buffer);\n    view.set(Array.from(content).map((c) => c.charCodeAt(0)));\n    this._result = buffer;\n    this._setReadyState(this.DONE);\n  };\n  fr.readAsDataURL(blob);\n};\n\n// from: https://stackoverflow.com/questions/42829838/react-native-atob-btoa-not-working-without-remote-js-debugging\n// const chars =\n//   \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n// const atob = (input = \"\") => {\n//   let str = input.replace(/=+$/, \"\");\n//   let output = \"\";\n\n//   if (str.length % 4 == 1) {\n//     throw new Error(\n//       \"'atob' failed: The string to be decoded is not correctly encoded.\"\n//     );\n//   }\n//   for (\n//     let bc = 0, bs = 0, buffer, i = 0;\n//     (buffer = str.charAt(i++));\n//     ~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n//       ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n//       : 0\n//   ) {\n//     buffer = chars.indexOf(buffer);\n//   }\n\n//   return output;\n// };\n\nexport default Base64;\n"
  },
  {
    "path": "app/components/ProgressIndicator.tsx",
    "content": "// @refresh reset\n\nimport React, { useState, useEffect } from \"react\";\nimport { View, Animated, StyleSheet } from \"react-native\";\nimport Svg, { Circle } from \"react-native-svg\";\n\nconst AnimatedCircle = Animated.createAnimatedComponent(Circle);\n\nconst numX = 4;\nconst numY = 5;\nconst total = numX * numY;\n\nconst styles = StyleSheet.create({\n  container: {\n    ...StyleSheet.absoluteFillObject,\n    alignItems: \"center\",\n    justifyContent: \"center\",\n  },\n});\nexport default function ProgressIndicator() {\n  const init = Array(total)\n    .fill(1)\n    .map((x) => ({ r: new Animated.Value(1), a: new Animated.Value(1) }));\n  const [anim, setAnim] = useState(init);\n\n  useEffect(() => {\n    console.log(\"update\");\n    const c = anim.map((v, i: number) => {\n      const t = 400 + Math.random() * 300;\n      const seq = Animated.parallel([\n        Animated.sequence([\n          Animated.timing(anim[i].r, { toValue: 3, duration: t - 50 }),\n          Animated.timing(anim[i].r, { toValue: 1, duration: t }),\n        ]),\n        Animated.sequence([\n          Animated.timing(anim[i].a, { toValue: 0.1, duration: t - 50 }),\n          Animated.timing(anim[i].a, { toValue: 1, duration: t }),\n        ]),\n      ]);\n      return Animated.loop(seq);\n    });\n    // console.log(c)\n    Animated.parallel(c).start();\n  }, []);\n\n  let circles = [];\n  const margin = 100 / (numX);\n  for (let x = 0; x < numX; x++) {\n    for (let y = 0; y < numY; y++) {\n      const i = y * numX + x;\n      circles.push({\n        x: (x + 0.5) * margin,\n        y: (y) * margin,\n        r: anim[i].r,\n        a: anim[i].a,\n      });\n    }\n  }\n\n  return (\n    <View style={styles.container}>\n      <Svg height=\"100%\" width=\"100%\" viewBox=\"0 0 100 100\">\n        {circles.map((c) => (\n          <AnimatedCircle\n            key={c.y * numX + c.x}\n            cx={c.x}\n            cy={c.y}\n            r={c.r}\n            fill=\"white\"\n            opacity={c.a}\n          />\n        ))}\n      </Svg>\n    </View>\n  );\n}\n"
  },
  {
    "path": "app/components/Server.tsx",
    "content": "import Base64 from \"./Base64\";\n\nconst URL = \"http://192.168.1.29:8080\";\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer) {\n  let binary = \"\";\n  const bytes = [].slice.call(new Uint8Array(buffer));\n  bytes.forEach((b) => (binary += String.fromCharCode(b)));\n  return Base64.btoa(binary);\n}\n\nfunction ping() {\n  fetch(URL + \"/ping\").catch((e) => console.error(e));\n}\n\nasync function cut(imageURI: string) {\n  const formData = new FormData();\n  formData.append(\"data\", {\n    uri: imageURI,\n    name: \"photo\",\n    type: \"image/jpg\",\n  });\n\n  const resp = await fetch(URL + \"/cut\", {\n    method: \"POST\",\n    body: formData,\n  }).then(async (res) => {\n    console.log(\"> converting...\");\n    const buffer = await res.arrayBuffer();\n    const base64Flag = \"data:image/png;base64,\";\n    const imageStr = arrayBufferToBase64(buffer);\n    return base64Flag + imageStr;\n  });\n\n  return resp;\n}\n\nasync function paste(imageURI: string) {\n  const formData = new FormData();\n  formData.append(\"data\", {\n    uri: imageURI,\n    name: \"photo\",\n    type: \"image/jpg\",\n  });\n\n  const resp = await fetch(URL + \"/paste\", {\n    method: \"POST\",\n    body: formData,\n  }).then((r) => r.json());\n\n  return resp;\n}\n\nexport default {\n  ping,\n  cut,\n  paste,\n};\n"
  },
  {
    "path": "app/package.json",
    "content": "{\n  \"main\": \"node_modules/expo/AppEntry.js\",\n  \"scripts\": {\n    \"start\": \"expo start\",\n    \"android\": \"expo start --android\",\n    \"ios\": \"expo start --ios\",\n    \"web\": \"expo start --web\",\n    \"eject\": \"expo eject\"\n  },\n  \"dependencies\": {\n    \"expo\": \"~37.0.3\",\n    \"expo-2d-context\": \"0.0.2\",\n    \"expo-asset\": \"~8.1.4\",\n    \"expo-camera\": \"~8.2.0\",\n    \"expo-gl\": \"~8.1.0\",\n    \"expo-image-manipulator\": \"~8.1.0\",\n    \"expo-permissions\": \"~8.1.0\",\n    \"mem\": \"^4.0.0\",\n    \"react\": \"~16.9.0\",\n    \"react-dom\": \"~16.9.0\",\n    \"react-native\": \"https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz\",\n    \"react-native-screens\": \"~2.2.0\",\n    \"react-native-svg\": \"11.0.1\",\n    \"react-native-web\": \"~0.11.7\"\n  },\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.8.6\",\n    \"@types/react\": \"~16.9.23\",\n    \"@types/react-native\": \"~0.61.17\",\n    \"babel-preset-expo\": \"~8.1.0\",\n    \"typescript\": \"~3.8.3\"\n  },\n  \"private\": true\n}\n"
  },
  {
    "path": "app/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"allowSyntheticDefaultImports\": true,\n    \"jsx\": \"react-native\",\n    \"lib\": [\"dom\", \"esnext\"],\n    \"moduleResolution\": \"node\",\n    \"noEmit\": true,\n    \"skipLibCheck\": true,\n    \"resolveJsonModule\": true,\n    \"strict\": true\n  }\n}\n"
  },
  {
    "path": "server/README.md",
    "content": "# AR Cut Paste local server\n\n## Setup\n\n```console\nvirtualenv -p python3.7 venv\nsource venv/bin/activate\npip install -r requirements.txt\n```\n\n## Run\n\nThe `BASNET_SERVICE_HOST` is optional (only needed if you've deployed the service\non a platform using an ingress gateway such as Knative / Cloud Run).\n\nReplace `123456` by your Photoshop remote connection password.\n\n```console\npython src/main.py \\\n    --basnet_service_ip=\"http://X.X.X.X\" \\\n    --basnet_service_host=\"basnet-http.default.example.com\" \\\n    --photoshop_password 123456\n```\n"
  },
  {
    "path": "server/requirements.txt",
    "content": "screenpoint==0.1.1\nphotoshop-connection==0.1.1\nFlask==1.1.1\nflask-cors==3.0.9\npyscreenshot==1.0\nPillow==8.3.2\nrequests==2.23.0"
  },
  {
    "path": "server/src/main.py",
    "content": "import io\nimport os\nfrom flask import Flask, request, jsonify, send_file\nfrom flask_cors import CORS\nfrom PIL import Image\nimport numpy as np\nimport time\nimport screenpoint\nfrom datetime import datetime\nimport pyscreenshot\nimport requests\nimport logging\nimport argparse\n\nimport ps\n\nlogging.basicConfig(level=logging.INFO)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--photoshop_password', default='123456')\nparser.add_argument('--basnet_service_ip', required=True, help=\"The BASNet service IP address\")\nparser.add_argument('--basnet_service_host', help=\"Optional, the BASNet service host\")\nargs = parser.parse_args()\n\nmax_view_size = 700\nmax_screenshot_size = 400\n\n# Initialize the Flask application.\napp = Flask(__name__)\nCORS(app)\n\n\n# Simple probe.\n@app.route('/', methods=['GET'])\ndef hello():\n    return 'Hello AR Cut Paste!'\n\n# Ping to wake up the BASNet service.\n@app.route('/ping', methods=['GET'])\ndef ping():\n    logging.info('ping')\n    r = requests.get(args.basnet_service_ip, headers={'Host': args.basnet_service_host})\n    logging.info(f'pong: {r.status_code} {r.content}')\n    return 'pong'\n\n\n# The cut endpoints performs the salience detection / background removal.\n# And store a copy of the result to be pasted later.\n@app.route('/cut', methods=['POST'])\ndef save():\n    start = time.time()\n    logging.info(' CUT')\n\n    # Convert string of image data to uint8.\n    if 'data' not in request.files:\n        return jsonify({\n            'status': 'error',\n            'error': 'missing file param `data`'\n        }), 400\n    data = request.files['data'].read()\n    if len(data) == 0:\n        return jsonify({'status:': 'error', 'error': 'empty image'}), 400\n\n    # Save debug locally.\n    with open('cut_received.jpg', 'wb') as f:\n        f.write(data)\n\n    # Send to BASNet service.\n    logging.info(' > sending to BASNet...')\n    headers = {}\n    if args.basnet_service_host is not None:\n        headers['Host'] = args.basnet_service_host\n    files= {'data': open('cut_received.jpg', 'rb')}\n    res = requests.post(args.basnet_service_ip, headers=headers, files=files )\n    # logging.info(res.status_code)\n\n    # Save mask locally.\n    logging.info(' > saving results...')\n    with open('cut_mask.png', 'wb') as f:\n        f.write(res.content)\n        # shutil.copyfileobj(res.raw, f)\n\n    logging.info(' > opening mask...')\n    mask = Image.open('cut_mask.png').convert(\"L\")\n\n    # Convert string data to PIL Image.\n    logging.info(' > compositing final image...')\n    ref = Image.open(io.BytesIO(data))\n    empty = Image.new(\"RGBA\", ref.size, 0)\n    img = Image.composite(ref, empty, mask)\n\n    # TODO: currently hack to manually scale up the images. Ideally this would\n    # be done respective to the view distance from the screen.\n    img_scaled = img.resize((img.size[0] * 3, img.size[1] * 3))\n\n    # Save locally.\n    logging.info(' > saving final image...')\n    img_scaled.save('cut_current.png')\n\n    # Save to buffer\n    buff = io.BytesIO()\n    img.save(buff, 'PNG')\n    buff.seek(0)\n\n    # Print stats\n    logging.info(f'Completed in {time.time() - start:.2f}s')\n\n    # Return data\n    return send_file(buff, mimetype='image/png')\n\n\n# The paste endpoints handles new paste requests.\n@app.route('/paste', methods=['POST'])\ndef paste():\n    start = time.time()\n    logging.info(' PASTE')\n\n    # Convert string of image data to uint8.\n    if 'data' not in request.files:\n        return jsonify({\n            'status': 'error',\n            'error': 'missing file param `data`'\n        }), 400\n    data = request.files['data'].read()\n    if len(data) == 0:\n        return jsonify({'status:': 'error', 'error': 'empty image'}), 400\n\n    # Save debug locally.\n    with open('paste_received.jpg', 'wb') as f:\n        f.write(data)\n\n    # Convert string data to PIL Image.\n    logging.info(' > loading image...')\n    view = Image.open(io.BytesIO(data))\n\n    # Ensure the view image size is under max_view_size.\n    if view.size[0] > max_view_size or view.size[1] > max_view_size:\n        view.thumbnail((max_view_size, max_view_size))\n\n    # Take screenshot with pyscreenshot.\n    logging.info(' > grabbing screenshot...')\n    screen = pyscreenshot.grab()\n    screen_width, screen_height = screen.size\n\n    # Ensure screenshot is under max size.\n    if screen.size[0] > max_screenshot_size or screen.size[1] > max_screenshot_size:\n        screen.thumbnail((max_screenshot_size, max_screenshot_size))\n\n    # Finds view centroid coordinates in screen space.\n    logging.info(' > finding projected point...')\n    view_arr = np.array(view.convert('L'))\n    screen_arr = np.array(screen.convert('L'))\n    # logging.info(f'{view_arr.shape}, {screen_arr.shape}')\n    x, y = screenpoint.project(view_arr, screen_arr, False)\n\n    found = x != -1 and y != -1\n\n    if found:\n        # Bring back to screen space\n        x = int(x / screen.size[0] * screen_width)\n        y = int(y / screen.size[1] * screen_height)\n        logging.info(f'{x}, {y}')\n\n        # Paste the current image in photoshop at these coordinates.\n        logging.info(' > sending to photoshop...')\n        name = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')\n        img_path = os.path.join(os.getcwd(), 'cut_current.png')\n        err = ps.paste(img_path, name, x, y, password=args.photoshop_password)\n        if err is not None:\n            logging.error('error sending to photoshop')\n            logging.error(err)\n            jsonify({'status': 'error sending to photoshop'})\n    else:\n        logging.info('screen not found')\n\n    # Print stats.\n    logging.info(f'Completed in {time.time() - start:.2f}s')\n\n    # Return status.\n    if found:\n        return jsonify({'status': 'ok'})\n    else:\n        return jsonify({'status': 'screen not found'})\n\n\nif __name__ == '__main__':\n    os.environ['FLASK_ENV'] = 'development'\n    port = int(os.environ.get('PORT', 8080))\n    app.run(debug=True, host='0.0.0.0', port=port)\n"
  },
  {
    "path": "server/src/ps.py",
    "content": "from photoshop import PhotoshopConnection\nfrom os.path import dirname, basename\n\n# TODO: This offset should be detected by getTopLeft() but the new version\n# of Photoshop doesn't seem to support executeActionGet so we put it\n# manually here in the meantime.\nSCREEN_PIXELS_DENSITY = 2\nDOC_OFFSET_X = 74 * SCREEN_PIXELS_DENSITY\nDOC_OFFSET_Y = 130 * SCREEN_PIXELS_DENSITY\nDOC_WIDTH = 2121\nDOC_HEIGHT = 1280\n\ndef paste(filename, name, x, y, password='123456'):\n\n    # There seem to be a bug on Windows where the path must be using unix separators.\n    # https://github.com/cyrildiagne/ar-cutpaste/issues/5\n    filename = filename.replace('\\\\', '/')\n\n    with PhotoshopConnection(password=password) as conn:\n        script = open(basename(dirname(__file__)) + '/script.js', 'r').read()\n        x -= DOC_WIDTH * 0.5 + DOC_OFFSET_X\n        y -= DOC_HEIGHT * 0.5 + DOC_OFFSET_Y\n        script += f'pasteImage(\"{filename}\", \"{name}\", {x}, {y})'\n        result = conn.execute(script)\n        print(result)\n        if result['status'] != 0:\n            return result\n    \n    return None\n"
  },
  {
    "path": "server/src/script.js",
    "content": "function pasteImage(filename, layerName, x, y) {\n  var fileRef = new File(filename);\n  var doc = app.activeDocument;\n\n  doc.artLayers.add();\n  var curr_file = app.open(fileRef);\n  curr_file.selection.selectAll();\n  curr_file.selection.copy();\n  curr_file.close();\n\n  doc.paste();\n  doc.activeLayer.name = layerName;\n  doc.activeLayer.translate(x, y);\n  try {\n    doc.activeLayer.move(doc.layers[doc.layers.length - 1], ElementPlacement.PLACEBEFORE);\n  } catch(e) {\n    alert(e);\n  }\n}\n\nfunction getTopLeft() {\n  try {\n    var r = new ActionReference();\n    executeActionGet(r)\n      .getObjectValue(stringIDToTypeID(\"viewInfo\"))\n      .getObjectValue(stringIDToTypeID(\"activeView\"))\n      .getObjectValue(stringIDToTypeID(\"globalBounds\"));\n    alert(t)\n  } catch (e) {\n    alert(e);\n  }\n}\n\n"
  }
]