[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-joelbarmettlerUZH--auto-tinder":3,"tool-joelbarmettlerUZH--auto-tinder":64},[4,17,27,35,43,56],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,3,"2026-04-05T11:01:52",[13,14,15],"开发框架","图像","Agent","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":23,"last_commit_at":24,"category_tags":25,"status":16},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",140436,2,"2026-04-05T23:32:43",[13,15,26],"语言模型",{"id":28,"name":29,"github_repo":30,"description_zh":31,"stars":32,"difficulty_score":23,"last_commit_at":33,"category_tags":34,"status":16},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[13,14,15],{"id":36,"name":37,"github_repo":38,"description_zh":39,"stars":40,"difficulty_score":23,"last_commit_at":41,"category_tags":42,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,26],{"id":44,"name":45,"github_repo":46,"description_zh":47,"stars":48,"difficulty_score":23,"last_commit_at":49,"category_tags":50,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[14,51,52,53,15,54,26,13,55],"数据工具","视频","插件","其他","音频",{"id":57,"name":58,"github_repo":59,"description_zh":60,"stars":61,"difficulty_score":10,"last_commit_at":62,"category_tags":63,"status":16},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,"2026-04-04T04:44:48",[15,14,13,26,54],{"id":65,"github_repo":66,"name":67,"description_en":68,"description_zh":69,"ai_summary_zh":69,"readme_en":70,"readme_zh":71,"quickstart_zh":72,"use_case_zh":73,"hero_image_url":74,"owner_login":75,"owner_name":76,"owner_avatar_url":77,"owner_bio":78,"owner_company":79,"owner_location":80,"owner_email":81,"owner_twitter":81,"owner_website":82,"owner_url":83,"languages":84,"stars":89,"forks":90,"last_commit_at":91,"license":92,"difficulty_score":10,"env_os":93,"env_gpu":93,"env_ram":93,"env_deps":94,"category_tags":101,"github_topics":102,"view_count":10,"oss_zip_url":81,"oss_zip_packed_at":81,"status":16,"created_at":109,"updated_at":110,"faqs":111,"releases":122},518,"joelbarmettlerUZH\u002Fauto-tinder","auto-tinder","🖖 Train an artificial intelligence to play tinder for you","auto-tinder 是一个旨在训练人工智能自动为你玩 Tinder 的趣味开源项目。它通过分析 Tinder 网页的内部 API 调用，结合 Python 和 TensorFlow 构建了一套自动化系统。这套系统不仅能下载附近用户的照片，还能利用预训练的 Inceptionv3 深度卷积神经网络来识别图片中的人物，并学习你的个人偏好，从而自动执行点赞或划走的决策。\n\nauto-tinder 主要解决了手动浏览交友软件耗时费力的痛点，但其核心定位是教育与实验。它非常适合对计算机视觉、API 逆向工程以及强化学习感兴趣的开发者或研究人员参考。通过 auto-tinder，你可以深入了解如何从前端抓包分析接口，再到后端模型训练的全流程。\n\n值得注意的是，auto-tinder 明确声明仅供娱乐和学习用途，严禁用于实际账号操作，因为这违反了 Tinder 的服务条款。如果你是技术爱好者，想探索 AI 在交互决策上的潜力，或者需要学习图像分类与 API 封装的技术实践，auto-tinder 的代码库将提供非常有价值的思路。但请务必遵守平台规则，切勿滥用。","# Auto-Tinder - Train an AI to swipe tinder for you\n\nAuto-tinder was created to train an API using Tensorflow and Python3 that learns your\ninterests and automatically plays the tinder swiping-game for you.\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_ebff1b564907.png)\n\nIn this document, I am going to explain the following steps that were needed to\ncreate auto-tinder:\n- analyze the tinder webpage to find out what internal API calls tinder makes, reconstruct the API calls in [Postman](https:\u002F\u002Fwww.getpostman.com\u002F) and analyze its content\n- Build a api wrapper class in python that uses the tinder api to like\u002Fdislike\u002Fmatch etc.\n- Download a bunch of images of people nearby\n- Write a simple mouse-click classifier to label our images\n- Develop a preprocessor that uses the tensorflow object detection API to only cut out the person\nin our image\n- Retrain inceptionv3, a deep convolutional neural network, to learn on our classified data\n- Use the classifier in combination with the tinder API wrapper to play tinder for us\n\n## Step 0: Motivation and disclaimer\n\nAuto tinder is a concept project purely created for fun and educational purposes. \nIt shall never be abused to harm anybody or spam the platform. The auto-tinder scripts\nshould not be used with your tinder profile since they surely violate tinders terms of service. \n\nI've written this piece of software mainly out of two reasons:\n\n1. Because I can and it was fun to create :)\n2. I wanted to find out whether an AI would actually be able to learn my\npreferences in the other sex and be a reliable left-right-swipe partner for me. \n3. (Purely fictional reason: I am a lazy person, so why not invest \n15 hours to code auto-tinder + 5 hours to label all images to save me a few hours of \nactually swiping tinder myself? Sounds like a good deal to me!)\n\n## Step 1: Analyze the tinder API\nThe first step is to find out how the tinder app communicates to tinders backend server. \nSince tinder offers a web version of its portal, this is as easy as going to \ntinder.com, opening up chrome devtools and have a quick look at the network protocol.\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_ee6c3a6c7f81.png)\n\nThe content shown in the picture above was from a request to [https:\u002F\u002Fapi.gotinder.com\u002Fv2\u002Frecs\u002Fcore](https:\u002F\u002Fapi.gotinder.com\u002Fv2\u002Frecs\u002Fcore) that\nis made when the tinder.com landing page is loading. Clearly, tinder has some sort\nof internal API that they are using to communicate between the front- and backend.\n\nWith analyzing the content of *\u002Frecs\u002Fcore*, it becomes clear that this API endpoint returns a list of \nuser profiles of people nearby. \n\nThe data includes (among many other fields), the following data:\n\n```json\n{\n    \"meta\": {\n        \"status\": 200\n    },\n    \"data\": {\n        \"results\": [\n            {\n                \"type\": \"user\",\n                \"user\": {\n                 \"_id\": \"4adfwe547s8df64df\",\n                    \"bio\": \"19y.\",\n                    \"birth_date\": \"1997-17-06T18:21:44.654Z\",\n                    \"name\": \"Anna\",\n                    \"photos\": [\n                        {\n                            \"id\": \"879sdfert-lskdföj-8asdf879-987sdflkj\",\n                            \"crop_info\": {\n                                \"user\": {\n                                    \"width_pct\": 1,\n                                    \"x_offset_pct\": 0,\n                                    \"height_pct\": 0.8,\n                                    \"y_offset_pct\": 0.08975463\n                                },\n                                \"algo\": {\n                                    \"width_pct\": 0.45674357,\n                                    \"x_offset_pct\": 0.984341657,\n                                    \"height_pct\": 0.234165403,\n                                    \"y_offset_pct\": 0.78902343\n                                },\n                                \"processed_by_bullseye\": true,\n                                \"user_customized\": false\n                            },\n                            \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002Foriginal_879sdfert-lskdföj-8asdf879-987sdflkj.jpeg\",\n                            \"processedFiles\": [\n                                {\n                                    \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002F640x800_879sdfert-lskdföj-8asdf879-987sdflkj.jpg\",\n                                    \"height\": 800,\n                                    \"width\": 640\n                                },\n                                {\n                                    \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002F320x400_879sdfert-lskdföj-8asdf879-987sdflkj.jpg\",\n                                    \"height\": 400,\n                                    \"width\": 320\n                                },\n                                {\n                                    \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002F172x216_879sdfert-lskdföj-8asdf879-987sdflkj.jpg\",\n                                    \"height\": 216,\n                                    \"width\": 172\n                                },\n                                {\n                                    \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002F84x106_879sdfert-lskdföj-8asdf879-987sdflkj.jpg\",\n                                    \"height\": 106,\n                                    \"width\": 84\n                                }\n                            ],\n                            \"last_update_time\": \"2019-10-03T16:18:30.532Z\",\n                            \"fileName\": \"879sdfert-lskdföj-8asdf879-987sdflkj.webp\",\n                            \"extension\": \"jpg,webp\",\n                            \"webp_qf\": [\n                                75\n                            ]\n                        }\n                    ],\n                    \"gender\": 1,\n                    \"jobs\": [],\n                    \"schools\": [],\n                    \"show_gender_on_profile\": false\n                },\n                \"facebook\": {\n                    \"common_connections\": [],\n                    \"connection_count\": 0,\n                    \"common_interests\": []\n                },\n                \"spotify\": {\n                    \"spotify_connected\": false\n                },\n                \"distance_mi\": 1,\n                \"content_hash\": \"slkadjfiuwejsdfuzkejhrsdbfskdzufiuerwer\",\n                \"s_number\": 9876540657341,\n                \"teaser\": {\n                    \"string\": \"\"\n                },\n                \"teasers\": [],\n                \"snap\": {\n                    \"snaps\": []\n                }\n            }\n        ]\n    }\n}\n           \n```\n\nA few things are very interesting here *(note that I changed all the data to not violate this persons privacy)*:\n\n- All images are publicly accessible. If you copy the image URL and open it in a private window, it still loads instantly - meaning that tinder\nuploads all user images publicly to the internet, free to be seen by anybody. \n- The original photos accessible via the API are extremely high resolution. If you upload a photo to tinder, they will scale it down for the in-app\nusage, but they store the original version publicly on their servers, accessible by anybody.\n- Even if you choose to \"show_gender_on_profile\", everybody can still see your gender via the API *(\"gender\": 1, where 1=Woman, 0=Man)*\n- If you send multiple requests to the tinder API consecutively, you always get different results (e.g. different profiles). We can therefore\njust call this endpoint repeatedly to \"farm\" a bunch of pictures that we can later use to train our neural network.\n\nWith analyzing the content headers, we quickly find our private API Keys: **X-Auth-Token**.\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_463ee2602899.png)\n\nWith copying this token and going over to Postman, we can validate that we can \nindeed freely communicate with the tinder API with just the right URL and our auth token.\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_dfc89d2c39c2.png)\n\nWith clicking a bit through tinders webapp, I quickly discover all relevant API endpoints:\n\n| Type | URL | Description  |\n| ------------- |:-------------:| -----:|\n| GET | \u002Fv2\u002Frecs\u002Fcore | Returns a list of people nearby |\n| GET | \u002Fv2\u002Fprofile?include=account%2Cuser | Returns all information about your own profile |\n| GET | \u002Fv2\u002Fmatches | Returns  a list of all people that have matched with you |\n| GET | \u002Flike\u002F{user_id} | Likes the person with the given user_id |\n| GET | \u002Fpass\u002F{user_id} | Passes the person with the given user_id |\n\n## Step 2: Building an API Wrapper in Python\n\nSo let's get into the code. We will use the python [Requests](https:\u002F\u002Frequests.kennethreitz.org\u002Fen\u002Fmaster\u002F) library to communicate with\nthe API and write an API wrapper class around it for convenience.\n\nSimilarly, we write a small Person class that takes the API response from Tinder representing a Person and \noffers a few basic interfaces to the tinder API.\n \n \nLet's start with the Person Class. It shall receive API data, a tinder-api object and save all relevant data\ninto instance variables. It shall further offer some basic features like \"like\" or \"dislike\" that make\na request to the tinder-api, which allows us to conveniently use \"some_person.like()\" in order to like\na profile we find interesting. \n\n```python\nimport datetime\nfrom geopy.geocoders import Nominatim\n\nTINDER_URL = \"https:\u002F\u002Fapi.gotinder.com\"\ngeolocator = Nominatim(user_agent=\"auto-tinder\")\nPROF_FILE = \".\u002Fimages\u002Funclassified\u002Fprofiles.txt\"\n\nclass Person(object):\n\n    def __init__(self, data, api):\n        self._api = api\n\n        self.id = data[\"_id\"]\n        self.name = data.get(\"name\", \"Unknown\")\n\n        self.bio = data.get(\"bio\", \"\")\n        self.distance = data.get(\"distance_mi\", 0) \u002F 1.60934\n\n        self.birth_date = datetime.datetime.strptime(data[\"birth_date\"], '%Y-%m-%dT%H:%M:%S.%fZ') if data.get(\n            \"birth_date\", False) else None\n        self.gender = [\"Male\", \"Female\", \"Unknown\"][data.get(\"gender\", 2)]\n\n        self.images = list(map(lambda photo: photo[\"url\"], data.get(\"photos\", [])))\n\n        self.jobs = list(\n            map(lambda job: {\"title\": job.get(\"title\", {}).get(\"name\"), \"company\": job.get(\"company\", {}).get(\"name\")}, data.get(\"jobs\", [])))\n        self.schools = list(map(lambda school: school[\"name\"], data.get(\"schools\", [])))\n\n        if data.get(\"pos\", False):\n            self.location = geolocator.reverse(f'{data[\"pos\"][\"lat\"]}, {data[\"pos\"][\"lon\"]}')\n\n\n    def __repr__(self):\n        return f\"{self.id}  -  {self.name} ({self.birth_date.strftime('%d.%m.%Y')})\"\n\n\n    def like(self):\n        return self._api.like(self.id)\n\n    def dislike(self):\n        return self._api.dislike(self.id)\n```\n\nOur API wrapper is not much more than a fancy way of calling the tinder API using a class:\n\n```python\nimport requests\n\nTINDER_URL = \"https:\u002F\u002Fapi.gotinder.com\"\n\nclass tinderAPI():\n\n    def __init__(self, token):\n        self._token = token\n\n    def profile(self):\n        data = requests.get(TINDER_URL + \"\u002Fv2\u002Fprofile?include=account%2Cuser\", headers={\"X-Auth-Token\": self._token}).json()\n        return Profile(data[\"data\"], self)\n\n    def matches(self, limit=10):\n        data = requests.get(TINDER_URL + f\"\u002Fv2\u002Fmatches?count={limit}\", headers={\"X-Auth-Token\": self._token}).json()\n        return list(map(lambda match: Person(match[\"person\"], self), data[\"data\"][\"matches\"]))\n\n    def like(self, user_id):\n        data = requests.get(TINDER_URL + f\"\u002Flike\u002F{user_id}\", headers={\"X-Auth-Token\": self._token}).json()\n        return {\n            \"is_match\": data[\"match\"],\n            \"liked_remaining\": data[\"likes_remaining\"]\n        }\n\n    def dislike(self, user_id):\n        requests.get(TINDER_URL + f\"\u002Fpass\u002F{user_id}\", headers={\"X-Auth-Token\": self._token}).json()\n        return True\n\n    def nearby_persons(self):\n        data = requests.get(TINDER_URL + \"\u002Fv2\u002Frecs\u002Fcore\", headers={\"X-Auth-Token\": self._token}).json()\n        return list(map(lambda user: Person(user[\"user\"], self), data[\"data\"][\"results\"]))\n```\n\nWe can now use the API to find people nearby and have a look at their profile, or even like all of them. \nReplace YOUR-API-TOKEN with the X-Auth-Token you found in the chrome dev console earlier.\n\n```python\n\nif __name__ == \"__main__\":\n    token = \"YOUR-API-TOKEN\"\n    api = tinderAPI(token)\n\n    while True:\n        persons = api.nearby_persons()\n        for person in persons:\n            print(person)\n            # person.like()\n```\n \n## Step 3: Download images of people nearby\n\nNext, we want to automatically download some images of people nearby that we can use for training our AI. \nWith 'some', I mean like 1500-2500 images. \n\nFirst, let's extend our Person class with a function that allows us to download images.\n\n```python\n# At the top of auto_tinder.py\nPROF_FILE = \".\u002Fimages\u002Funclassified\u002Fprofiles.txt\"\n\n# inside the Person-class\n    def download_images(self, folder=\".\", sleep_max_for=0):\n        with open(PROF_FILE, \"r\") as f:\n            lines = f.readlines()\n            if self.id in lines:\n                return\n        with open(PROF_FILE, \"a\") as f:\n            f.write(self.id+\"\\r\\n\")\n        index = -1\n        for image_url in self.images:\n            index += 1\n            req = requests.get(image_url, stream=True)\n            if req.status_code == 200:\n                with open(f\"{folder}\u002F{self.id}_{self.name}_{index}.jpeg\", \"wb\") as f:\n                    f.write(req.content)\n            sleep(random()*sleep_max_for)\n```\n\nNote that I added some random sleeps here and there, just because we will likely be blocked if we \nspam the tinder CDN and download many pictures in just a few seconds.\n\nWe write all the peoples profile IDs into a file called \"profiles.txt\". By first scanning the document\nwhether a particular person is already in there, we can skip people we already encountered, and\nwe ensure that we don't classify people several times (you will see later why this is a risk).\n\nWe can now just loop over nearby persons and download their images into an \"unclassified\" folder.\n\n```python\nif __name__ == \"__main__\":\n    token = \"YOUR-API-TOKEN\"\n    api = tinderAPI(token)\n\n    while True:\n        persons = api.nearby_persons()\n        for person in persons:\n            person.download_images(folder=\".\u002Fimages\u002Funclassified\", sleep_max_for=random()*3)\n            sleep(random()*10)\n        sleep(random()*10)\n```\n\nWe can now simply start this script and let it run for a few hours to get a few hundret profile images of people \nnearby. If you are a tinder PRO user, update your location now and then to get new people. \n\n## Step 4: Classify the images manually\n\nNow that we have a bunch of images to work with, let's build a really simple and ugly classifier. \n\nIt shall just loop over all the images in our \"unclassified\" folder and open the image in a GUI window.\nBy right-clicking a person, we can mark the person as \"dislike\", while a left-click marks the person\nas \"like\". This will be represented in the filename later on: *4tz3kjldfj3482.jpg* will be renamed\nto *1_4tz3kjldfj3482.jpg* if we mark the image as \"like\", or *0_4tz3kjldfj3482.jpg* otherwise.\nThe label like\u002Fdislike is encoded as 1\u002F0 in the beginning of the filenmae. \n\nLet's use tkinter to write this GUI quickly:\n\n```python\nfrom os import listdir, rename\nfrom os.path import isfile, join\nimport tkinter as tk\nfrom PIL import ImageTk, Image\n\nIMAGE_FOLDER = \".\u002Fimages\u002Funclassified\"\n\nimages = [f for f in listdir(IMAGE_FOLDER) if isfile(join(IMAGE_FOLDER, f))]\nunclassified_images = filter(lambda image: not (image.startswith(\"0_\") or image.startswith(\"1_\")), images)\ncurrent = None\n\ndef next_img():\n    global current, unclassified_images\n    try:\n        current = next(unclassified_images)\n    except StopIteration:\n        root.quit()\n    print(current)\n    pil_img = Image.open(IMAGE_FOLDER+\"\u002F\"+current)\n    width, height = pil_img.size\n    max_height = 1000\n    if height > max_height:\n        resize_factor = max_height \u002F height\n        pil_img = pil_img.resize((int(width*resize_factor), int(height*resize_factor)), resample=Image.LANCZOS)\n    img_tk = ImageTk.PhotoImage(pil_img)\n    img_label.img = img_tk\n    img_label.config(image=img_label.img)\n\ndef positive(arg):\n    global current\n    rename(IMAGE_FOLDER+\"\u002F\"+current, IMAGE_FOLDER+\"\u002F1_\"+current)\n    next_img()\n\ndef negative(arg):\n    global current\n    rename(IMAGE_FOLDER + \"\u002F\" + current, IMAGE_FOLDER + \"\u002F0_\" + current)\n    next_img()\n\n\nif __name__ == \"__main__\":\n\n    root = tk.Tk()\n\n    img_label = tk.Label(root)\n    img_label.pack()\n    img_label.bind(\"\u003CButton-1>\", positive)\n    img_label.bind(\"\u003CButton-3>\", negative)\n\n    btn = tk.Button(root, text='Next image', command=next_img)\n\n    next_img() # load first image\n\n    root.mainloop()\n```\n\nWe load all unclassified images into the \"unclassified_images\" list, open up a tkinter window, pack the first image into it\nby calling next_img() and resize the image to fit onto the screen. Then, we register two clicks, left-and right mouse buttons,\nand call the functions positive\u002Fnegative that renames the images according to their label and show the next image.\n\nUgly but effective. \n\n## Step 5: Develop a preprocessor to cut out only the person in our images\n\nFor the next step, we need to bring our image data into a format that allows us to \ndo a classification. There are a few difficulties we have to consider given our dataset.\n\n1. **Dataset Size:** Our Dataset is relatively small. We deal with +-2000 Images, which is considered\na very low amount of data, given the complexity of them (RGB Images with high resolution)\n2. **Data Variance:** The pictures sometimes contain people from behind, sometimes only faces, sometimes\nno people at all.\n3. **Data Noise:** Most pictures not only contain the person itself, but often the surrounding which can \nbe distracting four our AI. \n\nWe combat these challenges by:\n\n1. Converting our images to greyscale, to reduce the amount of information that our AI has to learn\nby a factor of 3 (RGB to G)\n2. Cutting out only the part of the image that actually contains the person, nothing else\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_79d629ba15d8.png)\n\nThe first part is as easy as using Pillow to open up our image and convert it to greyscale.\nFor the second part, we use the \n[Tensorflow Object Detection API](https:\u002F\u002Fgithub.com\u002Ftensorflow\u002Fmodels\u002Ftree\u002Fmaster\u002Fresearch\u002Fobject_detection)\nwith the mobilenet network architecture, pretrained on the coco dataset that also contains a label\nfor \"Person\".\n\nOur script for person detection has four parts: \n\n### Part 1: Opening the pretrained mobilenet coco dataset as a Tensorflow graph\n\nYou find the .bp file for the tensorflow mobilenet coco graph in my Github repository.\nLet's open it as a Tensorflow graph:\n\n```python\nimport tensorflow as tf\n\ndef open_graph():\n    detection_graph = tf.Graph()\n    with detection_graph.as_default():\n        od_graph_def = tf.GraphDef()\n        with tf.gfile.GFile('ssd_mobilenet_v1_coco_2017_11_17\u002Ffrozen_inference_graph.pb', 'rb') as fid:\n            serialized_graph = fid.read()\n            od_graph_def.ParseFromString(serialized_graph)\n            tf.import_graph_def(od_graph_def, name='')\n    return detection_graph\n```\n\n### Part 2: Load in images as numpy arrays\nWe use Pillow for image manipulation. Since tensorflow needs raw numpy arrays to work with the data, \nlet's write a small function that converts Pillow images to numpy arrays:\n\n```python\nimport numpy as np\n\ndef load_image_into_numpy_array(image):\n    (im_width, im_height) = image.size\n    return np.array(image.getdata()).reshape(\n        (im_height, im_width, 3)).astype(np.uint8)\n```\n\n### Part 3: Call object detection API\n\nThe next function takes an image and a tensorflow graph, runs a tensorflow session using it\nand return all informations about the detected classes (object types), bounding boxes \nand scores (certainty that the object was detected correctly). \n\n```python\nimport numpy as np\nfrom object_detection.utils import ops as utils_ops\nimport tensorflow as tf\n\ndef run_inference_for_single_image(image, sess):\n    ops = tf.get_default_graph().get_operations()\n    all_tensor_names = {output.name for op in ops for output in op.outputs}\n    tensor_dict = {}\n    for key in [\n        'num_detections', 'detection_boxes', 'detection_scores',\n        'detection_classes', 'detection_masks'\n    ]:\n        tensor_name = key + ':0'\n        if tensor_name in all_tensor_names:\n            tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(\n                tensor_name)\n    if 'detection_masks' in tensor_dict:\n        # The following processing is only for single image\n        detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\n        detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\n        # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n        real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\n        detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n        detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n        detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n            detection_masks, detection_boxes, image.shape[1], image.shape[2])\n        detection_masks_reframed = tf.cast(\n            tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n        # Follow the convention by adding back the batch dimension\n        tensor_dict['detection_masks'] = tf.expand_dims(\n            detection_masks_reframed, 0)\n    image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n    # Run inference\n    output_dict = sess.run(tensor_dict,\n                           feed_dict={image_tensor: image})\n\n    # all outputs are float32 numpy arrays, so convert types as appropriate\n    output_dict['num_detections'] = int(output_dict['num_detections'][0])\n    output_dict['detection_classes'] = output_dict[\n        'detection_classes'][0].astype(np.int64)\n    output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n    output_dict['detection_scores'] = output_dict['detection_scores'][0]\n    if 'detection_masks' in output_dict:\n        output_dict['detection_masks'] = output_dict['detection_masks'][0]\n    return output_dict\n```\n\n### Part 4: Bringing it all together to find the person\n\nThe last step is to write a function that takes an image path, opens it using Pillow,\ncalls the object detection api interface and crops the image according to the \ndetected persons bounding box.\n\n```python\nimport numpy as np\nfrom PIL import Image\n\nPERSON_CLASS = 1\nSCORE_THRESHOLD = 0.5\n\ndef get_person(image_path, sess):\n    img = Image.open(image_path)\n    image_np = load_image_into_numpy_array(img)\n    image_np_expanded = np.expand_dims(image_np, axis=0)\n    output_dict = run_inference_for_single_image(image_np_expanded, sess)\n\n    persons_coordinates = []\n    for i in range(len(output_dict[\"detection_boxes\"])):\n        score = output_dict[\"detection_scores\"][i]\n        classtype = output_dict[\"detection_classes\"][i]\n        if score > SCORE_THRESHOLD and classtype == PERSON_CLASS:\n            persons_coordinates.append(output_dict[\"detection_boxes\"][i])\n\n    w, h = img.size\n    for person_coordinate in persons_coordinates:\n        cropped_img = img.crop((\n            int(w * person_coordinate[1]),\n            int(h * person_coordinate[0]),\n            int(w * person_coordinate[3]),\n            int(h * person_coordinate[2]),\n        ))\n        return cropped_img\n    return None\n```\n\n### Part 5: Move all images into according classified folder\n\nAs a last step, we write a script that loops over all images in the \"unclassified\" folder,\nchecks whether they have an encoded label in the name copies the image in the according\n\"classified\" folder with applying the previously developed preprocessing steps:\n\n```python\nimport os\nimport person_detector\nimport tensorflow as tf\n\nIMAGE_FOLDER = \".\u002Fimages\u002Funclassified\"\nPOS_FOLDER = \".\u002Fimages\u002Fclassified\u002Fpositive\"\nNEG_FOLDER = \".\u002Fimages\u002Fclassified\u002Fnegative\"\n\n\nif __name__ == \"__main__\":\n    detection_graph = person_detector.open_graph()\n\n    images = [f for f in os.listdir(IMAGE_FOLDER) if os.path.isfile(os.path.join(IMAGE_FOLDER, f))]\n    positive_images = filter(lambda image: (image.startswith(\"1_\")), images)\n    negative_images = filter(lambda image: (image.startswith(\"0_\")), images)\n\n    with detection_graph.as_default():\n        with tf.Session() as sess:\n\n            for pos in positive_images:\n                old_filename = IMAGE_FOLDER + \"\u002F\" + pos\n                new_filename = POS_FOLDER + \"\u002F\" + pos[:-5] + \".jpg\"\n                if not os.path.isfile(new_filename):\n                    img = person_detector.get_person(old_filename, sess)\n                    if not img:\n                        continue\n                    img = img.convert('L')\n                    img.save(new_filename, \"jpeg\")\n\n            for neg in negative_images:\n                old_filename = IMAGE_FOLDER + \"\u002F\" + neg\n                new_filename = NEG_FOLDER + \"\u002F\" + neg[:-5] + \".jpg\"\n                if not os.path.isfile(new_filename):\n                    img = person_detector.get_person(old_filename, sess)\n                    if not img:\n                        continue\n                    img = img.convert('L')\n                    img.save(new_filename, \"jpeg\")\n```\n\nWhenver we run this script, all labeled images are being processed and moved into corresponding\nsubfolders in the \"classified\" directory. \n\n## Step 6: Retrain inceptionv3 and write a classifier\n\nFor the retraining part, we'll just use tensorflows [retrain.py](https:\u002F\u002Fgithub.com\u002Ftensorflow\u002Fhub\u002Fblob\u002Fmaster\u002Fexamples\u002Fimage_retraining\u002Fretrain.py)\nscript with the inceptionv3 model.\n\nCall the script in your project root directory with the following parameters:\n\n```shell\npython retrain.py --bottleneck_dir=tf\u002Ftraining_data\u002Fbottlenecks --model_dir=tf\u002Ftraining_data\u002Finception --summaries_dir=tf\u002Ftraining_data\u002Fsummaries\u002Fbasic --output_graph=tf\u002Ftraining_output\u002Fretrained_graph.pb --output_labels=tf\u002Ftraining_output\u002Fretrained_labels.txt --image_dir=.\u002Fimages\u002Fclassified --how_many_training_steps=50000 --testing_percentage=20 --learning_rate=0.001\n```\n\nThe learning takes roughly 15 minutes on a GTX 1080 ti, with a final accuracy of about 80% for my\nlabeled dataset, but this heavily depends on the quality of your input data and your labeling. \n\nThe result of the training process is a retrained inceptionV3 model in the \"tf\u002Ftraining_output\u002Fretrained_graph.pb\"\nfile. We must now write a Classifier class that efficiently uses the new weights in the tensorflow\ngraph to make a classification prediction. \n\nLet's write a Classifier-Class that opens the graph as a session and offers a \"classify\" method\nwith an image file that returns a dict with certainty values matching our labels \"positive\" and \"negative\".\n\nThe class takes as input both the path to the graph as well as the path to the label file, both\nsitting in our \"tf\u002Ftraining_output\u002F\" folder. We develop helper functions for converting\nan image file to a tensor that we can feed into our graph, a helper function for loading the graph and\nlabels and an important little function to close our graph after we are done using it. \n```python\nimport numpy as np\nimport tensorflow as tf\n\nclass Classifier():\n    def __init__(self, graph, labels):\n\n        self._graph = self.load_graph(graph)\n        self._labels = self.load_labels(labels)\n\n        self._input_operation = self._graph.get_operation_by_name(\"import\u002FPlaceholder\")\n        self._output_operation = self._graph.get_operation_by_name(\"import\u002Ffinal_result\")\n\n        self._session = tf.Session(graph=self._graph)\n\n    def classify(self, file_name):\n        t = self.read_tensor_from_image_file(file_name)\n\n        # Open up a new tensorflow session and run it on the input\n        results = self._session.run(self._output_operation.outputs[0], {self._input_operation.outputs[0]: t})\n        results = np.squeeze(results)\n\n        # Sort the output predictions by prediction accuracy\n        top_k = results.argsort()[-5:][::-1]\n\n        result = {}\n        for i in top_k:\n            result[self._labels[i]] = results[i]\n\n        # Return sorted result tuples\n        return result\n\n    def close(self):\n        self._session.close()\n\n\n    @staticmethod\n    def load_graph(model_file):\n        graph = tf.Graph()\n        graph_def = tf.GraphDef()\n        with open(model_file, \"rb\") as f:\n            graph_def.ParseFromString(f.read())\n        with graph.as_default():\n            tf.import_graph_def(graph_def)\n        return graph\n\n    @staticmethod\n    def load_labels(label_file):\n        label = []\n        proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()\n        for l in proto_as_ascii_lines:\n            label.append(l.rstrip())\n        return label\n\n    @staticmethod\n    def read_tensor_from_image_file(file_name,\n                                    input_height=299,\n                                    input_width=299,\n                                    input_mean=0,\n                                    input_std=255):\n        input_name = \"file_reader\"\n        file_reader = tf.read_file(file_name, input_name)\n        image_reader = tf.image.decode_jpeg(\n            file_reader, channels=3, name=\"jpeg_reader\")\n        float_caster = tf.cast(image_reader, tf.float32)\n        dims_expander = tf.expand_dims(float_caster, 0)\n        resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])\n        normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])\n        sess = tf.Session()\n        result = sess.run(normalized)\n        return result\n```\n\n## Step 7: Use all this to actually auto-play tinder\n\nNow that we have our classifier in place, let's extend the \"Person\" class from\nearlier and extend it with a \"predict_likeliness\" function that uses a classifier\ninstance to verify whether a given person should be liked or not.\n\n```python\n# In the Person class\n\n    def predict_likeliness(self, classifier, sess):\n        ratings = []\n        for image in self.images:\n            req = requests.get(image, stream=True)\n            tmp_filename = f\".\u002Fimages\u002Ftmp\u002Frun.jpg\"\n            if req.status_code == 200:\n                with open(tmp_filename, \"wb\") as f:\n                    f.write(req.content)\n            img = person_detector.get_person(tmp_filename, sess)\n            if img:\n                img = img.convert('L')\n                img.save(tmp_filename, \"jpeg\")\n                certainty = classifier.classify(tmp_filename)\n                pos = certainty[\"positive\"]\n                ratings.append(pos)\n        ratings.sort(reverse=True)\n        ratings = ratings[:5]\n        if len(ratings) == 0:\n            return 0.001\n        return ratings[0]*0.6 + sum(ratings[1:])\u002Flen(ratings[1:])*0.4\n\n```\n\nNow we have to bring all the puzzle pieces together. \n\nFirst, let's initialize the tinder API with our api token. Then, we open up\nour classification tensorflow graph as a tensorflow session using our\nretrained graph and labels. Then, we fetch persons nearby and make a \nlikeliness prediction. \n\nAs a little bonus, I added a likeliness-multiplier of 1.2 if the person\non Tinder goes to the same university as I do, so that I am more likely \nto match with local students. \n\nFor all people that have a predicted likeliness score of 0.8, I call a like, \nfor all the other a dislike.\n\nI developed the script to auto-play for the next 2 hours after it is started.\n\n```python\nfrom likeliness_classifier import Classifier\nimport person_detector\nimport tensorflow as tf\nfrom time import time\n\nif __name__ == \"__main__\":\n    token = \"YOUR-API-TOKEN\"\n    api = tinderAPI(token)\n\n    detection_graph = person_detector.open_graph()\n    with detection_graph.as_default():\n        with tf.Session() as sess:\n\n            classifier = Classifier(graph=\".\u002Ftf\u002Ftraining_output\u002Fretrained_graph.pb\",\n                                    labels=\".\u002Ftf\u002Ftraining_output\u002Fretrained_labels.txt\")\n\n            end_time = time() + 60*60*2\n            while time() \u003C end_time:\n                try:\n                    persons = api.nearby_persons()\n                    pos_schools = [\"Universität Zürich\", \"University of Zurich\", \"UZH\"]\n\n                    for person in persons:\n                        score = person.predict_likeliness(classifier, sess)\n\n                        for school in pos_schools:\n                            if school in person.schools:\n                                print()\n                                score *= 1.2\n\n                        print(\"-------------------------\")\n                        print(\"ID: \", person.id)\n                        print(\"Name: \", person.name)\n                        print(\"Schools: \", person.schools)\n                        print(\"Images: \", person.images)\n                        print(score)\n\n                        if score > 0.8:\n                            res = person.like()\n                            print(\"LIKE\")\n                        else:\n                            res = person.dislike()\n                            print(\"DISLIKE\")\n                except Exception:\n                    pass\n\n    classifier.close()\n```\n\nThat's it! We can now let our script run for as long as we like\nand play tinder without abusing our thumb!\n\nIf you have questions or found bugs, feel free to contribute\nto my [Github Repository](https:\u002F\u002Fgithub.com\u002FjoelbarmettlerUZH\u002Fauto-tinder).\n\n# License\nMIT License\n\nCopyright (c) 2018 Joel Barmettler\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\u002For sell \ncopies of the Software, and to permit persons to whom the Software is furnished \nto do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in \nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS \nOR IMPLIED, 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\nBy the way, I am an [AI Engineer from Zurich](https:\u002F\u002Fjoelbarmettler.xyz\u002F) and do [AI research](https:\u002F\u002Fjoelbarmettler.xyz\u002Fresearch\u002F), [AI Keynote Speaker](https:\u002F\u002Fjoelbarmettler.xyz\u002Fauftritte\u002F) and [AI Webinars](https:\u002F\u002Fjoelbarmettler.xyz\u002Fauftritte\u002Fwebinar-2024-rewind-2025-ausblick\u002F) in Zurich, Switzerland!\n","# Auto-Tinder - 训练 AI 帮你刷 Tinder（约会应用）\n\nAuto-tinder 旨在利用 TensorFlow（一种机器学习框架）和 Python3 训练一个 API（应用程序编程接口），该 API 能够学习你的兴趣，并自动为你完成 Tinder（约会应用）的滑动匹配游戏。\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_ebff1b564907.png)\n\n在这份文档中，我将介绍创建 Auto-tinder 所需的以下步骤：\n- 分析 Tinder 网页以找出 Tinder 进行的内部 API（应用程序编程接口）调用，在 [Postman](https:\u002F\u002Fwww.getpostman.com\u002F)（API 测试工具）中重建这些 API 调用并分析其内容\n- 用 Python 构建一个 API（应用程序编程接口）包装类，该类使用 Tinder API（应用程序编程接口）来执行喜欢\u002F不喜欢\u002F匹配等操作\n- 下载一批附近人物的图片\n- 编写一个简单的鼠标点击分类器来为我们的图片打标签\n- 开发一个预处理器，利用 TensorFlow 目标检测 API（应用程序编程接口）仅裁剪出图片中的人物\n- 重新训练 InceptionV3（一种深度卷积神经网络），使其在我们的分类数据上进行学习\n- 结合分类器和 Tinder API（应用程序编程接口）包装类来为我们玩 Tinder\n\n## 第 0 步：动机与免责声明\n\nAuto-tinder 是一个纯粹为了娱乐和教育目的而创建的概念项目。它绝不应被滥用去伤害任何人或骚扰平台。Auto-tinder 脚本不应与您的 Tinder 个人资料配合使用，因为它们肯定违反了 Tinder 的服务条款（Terms of Service）。\n\n我编写这段软件主要有两个主要原因：\n\n1. 因为我能做到，而且创造它很有趣 :)\n2. 我想弄清楚 AI 是否真的能够学习我对异性的偏好，并成为我可靠的左右滑动伴侣。\n3. （纯属虚构的理由：我是个懒人，为什么不投入 15 小时编写 Auto-tinder + 5 小时标注所有图片，从而节省我自己实际刷 Tinder 的几个小时呢？对我来说这听起来是一笔划算的交易！）\n\n## 第一步：分析 Tinder API (应用程序接口)\n第一步是找出 Tinder 应用程序如何与其后端服务器通信。由于 Tinder 提供了其门户的网页版本，这很简单，只需访问 tinder.com，打开 Chrome DevTools 并快速查看网络协议即可。\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_ee6c3a6c7f81.png)\n\n上图显示的内容来自当 tinder.com 主页加载时发出的对 [https:\u002F\u002Fapi.gotinder.com\u002Fv2\u002Frecs\u002Fcore](https:\u002F\u002Fapi.gotinder.com\u002Fv2\u002Frecs\u002Fcore) 的请求。显然，Tinder 拥有某种内部 API (应用程序接口)，用于在前端和后端之间进行通信。\n\n通过分析 *\u002Frecs\u002Fcore* 的内容，可以清楚地看到这个 API 端点返回了附近用户个人资料列表。\n\n数据包含（除许多其他字段外）以下数据：\n\n```json\n{\n    \"meta\": {\n        \"status\": 200\n    },\n    \"data\": {\n        \"results\": [\n            {\n                \"type\": \"user\",\n                \"user\": {\n                 \"_id\": \"4adfwe547s8df64df\",\n                    \"bio\": \"19y.\",\n                    \"birth_date\": \"1997-17-06T18:21:44.654Z\",\n                    \"name\": \"Anna\",\n                    \"photos\": [\n                        {\n                            \"id\": \"879sdfert-lskdföj-8asdf879-987sdflkj\",\n                            \"crop_info\": {\n                                \"user\": {\n                                    \"width_pct\": 1,\n                                    \"x_offset_pct\": 0,\n                                    \"height_pct\": 0.8,\n                                    \"y_offset_pct\": 0.08975463\n                                },\n                                \"algo\": {\n                                    \"width_pct\": 0.45674357,\n                                    \"x_offset_pct\": 0.984341657,\n                                    \"height_pct\": 0.234165403,\n                                    \"y_offset_pct\": 0.78902343\n                                },\n                                \"processed_by_bullseye\": true,\n                                \"user_customized\": false\n                            },\n                            \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002Foriginal_879sdfert-lskdföj-8asdf879-987sdflkj.jpeg\",\n                            \"processedFiles\": [\n                                {\n                                    \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002F640x800_879sdfert-lskdföj-8asdf879-987sdflkj.jpg\",\n                                    \"height\": 800,\n                                    \"width\": 640\n                                },\n                                {\n                                    \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002F320x400_879sdfert-lskdföj-8asdf879-987sdflkj.jpg\",\n                                    \"height\": 400,\n                                    \"width\": 320\n                                },\n                                {\n                                    \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002F172x216_879sdfert-lskdföj-8asdf879-987sdflkj.jpg\",\n                                    \"height\": 216,\n                                    \"width\": 172\n                                },\n                                {\n                                    \"url\": \"https:\u002F\u002Fimages-ssl.gotinder.com\u002F4adfwe547s8df64df\u002F84x106_879sdfert-lskdföj-8asdf879-987sdflkj.jpg\",\n                                    \"height\": 106,\n                                    \"width\": 84\n                                }\n                            ],\n                            \"last_update_time\": \"2019-10-03T16:18:30.532Z\",\n                            \"fileName\": \"879sdfert-lskdföj-8asdf879-987sdflkj.webp\",\n                            \"extension\": \"jpg,webp\",\n                            \"webp_qf\": [\n                                75\n                            ]\n                        }\n                    ],\n                    \"gender\": 1,\n                    \"jobs\": [],\n                    \"schools\": [],\n                    \"show_gender_on_profile\": false\n                },\n                \"facebook\": {\n                    \"common_connections\": [],\n                    \"connection_count\": 0,\n                    \"common_interests\": []\n                },\n                \"spotify\": {\n                    \"spotify_connected\": false\n                },\n                \"distance_mi\": 1,\n                \"content_hash\": \"slkadjfiuwejsdfuzkejhrsdbfskdzufiuerwer\",\n                \"s_number\": 9876540657341,\n                \"teaser\": {\n                    \"string\": \"\"\n                },\n                \"teasers\": [],\n                \"snap\": {\n                    \"snaps\": []\n                }\n            }\n        ]\n    }\n}\n           \n```\n\n这里有几点非常有趣 *（注意我已更改所有数据以不侵犯此人的隐私）*：\n\n- 所有图片均可公开访问。如果你复制图片 URL 并在无痕窗口中打开它，它仍然会立即加载——这意味着 Tinder 将所有用户图片公开上传到互联网，任何人都可以看到。\n- 通过 API (应用程序接口) 可访问的原始照片分辨率极高。如果你向 Tinder 上传照片，他们会对应用内使用进行缩放，但他们会将原始版本公开存储在服务器上，任何人都可以访问。\n- 即使你选择“在个人资料中显示性别”，其他人仍可以通过 API (应用程序接口) 看到你的性别 *(\"gender\": 1，其中 1=女性，0=男性)*\n- 如果你连续向 Tinder API (应用程序接口) 发送多个请求，你总是会得到不同的结果（例如不同的个人资料）。因此，我们可以简单地重复调用此端点来“采集”一批图片，稍后用于训练我们的神经网络。\n\n通过分析请求头信息，我们很快找到了私有的 API 密钥：**X-Auth-Token**。\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_463ee2602899.png)\n\n复制此令牌并转到 Postman，我们可以验证仅凭正确的 URL 和认证令牌，我们确实可以自由地与 Tinder API (应用程序接口) 通信。\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_dfc89d2c39c2.png)\n\n通过点击 Tinder Web 应用的一些部分，我很快发现了所有相关的 API 端点：\n\n| 类型 | URL | 描述 |\n| ------------- |:-------------:| -----:|\n| GET | \u002Fv2\u002Frecs\u002Fcore | 返回附近人员列表 |\n| GET | \u002Fv2\u002Fprofile?include=account%2Cuser | 返回关于您自己个人资料的所有信息 |\n| GET | \u002Fv2\u002Fmatches | 返回与您匹配的所有人员列表 |\n| GET | \u002Flike\u002F{user_id} | 喜欢给定 user_id 的人员 |\n| GET | \u002Fpass\u002F{user_id} | 跳过给定 user_id 的人员 |\n\n## 第二步：在 Python 中构建 API（应用程序编程接口）封装\n\n让我们开始进入代码部分。我们将使用 Python [Requests](https:\u002F\u002Frequests.kennethreitz.org\u002Fen\u002Fmaster\u002F) 库与 API（应用程序编程接口）进行通信，并围绕它编写一个 API 封装类以便于使用。\n\n同样，我们编写了一个小型的 Person 类，它接收来自 Tinder 的 API 响应以表示一个人员（Person），并为 tinder API 提供了一些基本接口。\n\n让我们从 Person 类开始。它将接收 API 数据、一个 tinder-api 对象，并将所有相关数据保存到实例变量中。它还将提供一些基本功能，如“喜欢”或“不喜欢”，这些功能会向 tinder-api 发起请求，这使我们能够方便地使用 \"some_person.like()\" 来对我们感兴趣的个人资料点赞。\n\n```python\nimport datetime\nfrom geopy.geocoders import Nominatim\n\nTINDER_URL = \"https:\u002F\u002Fapi.gotinder.com\"\ngeolocator = Nominatim(user_agent=\"auto-tinder\")\nPROF_FILE = \".\u002Fimages\u002Funclassified\u002Fprofiles.txt\"\n\nclass Person(object):\n\n    def __init__(self, data, api):\n        self._api = api\n\n        self.id = data[\"_id\"]\n        self.name = data.get(\"name\", \"Unknown\")\n\n        self.bio = data.get(\"bio\", \"\")\n        self.distance = data.get(\"distance_mi\", 0) \u002F 1.60934\n\n        self.birth_date = datetime.datetime.strptime(data[\"birth_date\"], '%Y-%m-%dT%H:%M:%S.%fZ') if data.get(\n            \"birth_date\", False) else None\n        self.gender = [\"Male\", \"Female\", \"Unknown\"][data.get(\"gender\", 2)]\n\n        self.images = list(map(lambda photo: photo[\"url\"], data.get(\"photos\", [])))\n\n        self.jobs = list(\n            map(lambda job: {\"title\": job.get(\"title\", {}).get(\"name\"), \"company\": job.get(\"company\", {}).get(\"name\")}, data.get(\"jobs\", [])))\n        self.schools = list(map(lambda school: school[\"name\"], data.get(\"schools\", [])))\n\n        if data.get(\"pos\", False):\n            self.location = geolocator.reverse(f'{data[\"pos\"][\"lat\"]}, {data[\"pos\"][\"lon\"]}')\n\n\n    def __repr__(self):\n        return f\"{self.id}  -  {self.name} ({self.birth_date.strftime('%d.%m.%Y')})\"\n\n\n    def like(self):\n        return self._api.like(self.id)\n\n    def dislike(self):\n        return self._api.dislike(self.id)\n```\n\n我们的 API 封装类不过是使用类 (Class) 来调用 tinder API 的一种更优雅的方式：\n\n```python\nimport requests\n\nTINDER_URL = \"https:\u002F\u002Fapi.gotinder.com\"\n\nclass tinderAPI():\n\n    def __init__(self, token):\n        self._token = token\n\n    def profile(self):\n        data = requests.get(TINDER_URL + \"\u002Fv2\u002Fprofile?include=account%2Cuser\", headers={\"X-Auth-Token\": self._token}).json()\n        return Profile(data[\"data\"], self)\n\n    def matches(self, limit=10):\n        data = requests.get(TINDER_URL + f\"\u002Fv2\u002Fmatches?count={limit}\", headers={\"X-Auth-Token\": self._token}).json()\n        return list(map(lambda match: Person(match[\"person\"], self), data[\"data\"][\"matches\"]))\n\n    def like(self, user_id):\n        data = requests.get(TINDER_URL + f\"\u002Flike\u002F{user_id}\", headers={\"X-Auth-Token\": self._token}).json()\n        return {\n            \"is_match\": data[\"match\"],\n            \"liked_remaining\": data[\"likes_remaining\"]\n        }\n\n    def dislike(self, user_id):\n        requests.get(TINDER_URL + f\"\u002Fpass\u002F{user_id}\", headers={\"X-Auth-Token\": self._token}).json()\n        return True\n\n    def nearby_persons(self):\n        data = requests.get(TINDER_URL + \"\u002Fv2\u002Frecs\u002Fcore\", headers={\"X-Auth-Token\": self._token}).json()\n        return list(map(lambda user: Person(user[\"user\"], self), data[\"data\"][\"results\"]))\n```\n\n我们现在可以使用 API 查找附近的人并查看他们的个人资料，甚至可以给他们全部点赞。将 YOUR-API-TOKEN 替换为你之前在 chrome 开发者控制台中找到的 X-Auth-Token（令牌）。\n\n```python\n\nif __name__ == \"__main__\":\n    token = \"YOUR-API-TOKEN\"\n    api = tinderAPI(token)\n\n    while True:\n        persons = api.nearby_persons()\n        for person in persons:\n            print(person)\n            # person.like()\n```\n \n## 第三步：下载附近人员的图片\n\n接下来，我们希望自动下载一些附近人员的图片，我们可以用它们来训练我们的 AI（人工智能）。这里的“一些”，我指的是大约 1500-2500 张图片。\n\n首先，让我们在 Person 类中添加一个允许我们下载图片的函数。\n\n```python\n# At the top of auto_tinder.py\nPROF_FILE = \".\u002Fimages\u002Funclassified\u002Fprofiles.txt\"\n\n# inside the Person-class\n    def download_images(self, folder=\".\", sleep_max_for=0):\n        with open(PROF_FILE, \"r\") as f:\n            lines = f.readlines()\n            if self.id in lines:\n                return\n        with open(PROF_FILE, \"a\") as f:\n            f.write(self.id+\"\\r\\n\")\n        index = -1\n        for image_url in self.images:\n            index += 1\n            req = requests.get(image_url, stream=True)\n            if req.status_code == 200:\n                with open(f\"{folder}\u002F{self.id}_{self.name}_{index}.jpeg\", \"wb\") as f:\n                    f.write(req.content)\n            sleep(random()*sleep_max_for)\n```\n\n请注意，我在这里和那里添加了一些随机的休眠时间，因为如果我们向 tinder CDN（内容分发网络）发送过多请求并在几秒钟内下载大量图片，很可能会被封锁。\n\n我们将所有人的个人资料 ID 写入名为 \"profiles.txt\" 的文件中。通过首先扫描文档以确定特定人员是否已经存在其中，我们可以跳过我们已经遇到过的人，并确保我们不会对同一个人进行分类多次（你稍后会明白为什么这是一个风险）。\n\n我们现在只需遍历附近的人员并将他们的图片下载到 \"unclassified\" 文件夹中。\n\n```python\nif __name__ == \"__main__\":\n    token = \"YOUR-API-TOKEN\"\n    api = tinderAPI(token)\n\n    while True:\n        persons = api.nearby_persons()\n        for person in persons:\n            person.download_images(folder=\".\u002Fimages\u002Funclassified\", sleep_max_for=random()*3)\n            sleep(random()*10)\n        sleep(random()*10)\n```\n\n我们现在可以简单地启动此脚本并让其运行几个小时，以获取几百张附近人员的个人资料图片。如果你是 tinder PRO 用户，请时不时更新你的位置以获取新的人员。\n\n## 步骤 4：手动分类图像\n\n既然我们已经有了大量可供处理的图像，让我们构建一个非常简单且简陋的分类器。\n\n它只需遍历我们 \"未分类\" 文件夹中的所有图像，并在 GUI（图形用户界面）窗口中打开图像。通过右键点击人物，我们可以将该人物标记为“不喜欢”，而左键点击则标记为“喜欢”。这将在文件名中体现：如果我们标记图像为“喜欢”，*4tz3kjldfj3482.jpg* 将被重命名为 *1_4tz3kjldfj3482.jpg*，否则为 *0_4tz3kjldfj3482.jpg*。标签“喜欢\u002F不喜欢”在文件名的开头被编码为 1\u002F0。\n\n让我们使用 tkinter（Python 标准 GUI 库）快速编写这个 GUI：\n\n```python\nfrom os import listdir, rename\nfrom os.path import isfile, join\nimport tkinter as tk\nfrom PIL import ImageTk, Image\n\nIMAGE_FOLDER = \".\u002Fimages\u002Funclassified\"\n\nimages = [f for f in listdir(IMAGE_FOLDER) if isfile(join(IMAGE_FOLDER, f))]\nunclassified_images = filter(lambda image: not (image.startswith(\"0_\") or image.startswith(\"1_\")), images)\ncurrent = None\n\ndef next_img():\n    global current, unclassified_images\n    try:\n        current = next(unclassified_images)\n    except StopIteration:\n        root.quit()\n    print(current)\n    pil_img = Image.open(IMAGE_FOLDER+\"\u002F\"+current)\n    width, height = pil_img.size\n    max_height = 1000\n    if height > max_height:\n        resize_factor = max_height \u002F height\n        pil_img = pil_img.resize((int(width*resize_factor), int(height*resize_factor)), resample=Image.LANCZOS)\n    img_tk = ImageTk.PhotoImage(pil_img)\n    img_label.img = img_tk\n    img_label.config(image=img_label.img)\n\ndef positive(arg):\n    global current\n    rename(IMAGE_FOLDER+\"\u002F\"+current, IMAGE_FOLDER+\"\u002F1_\"+current)\n    next_img()\n\ndef negative(arg):\n    global current\n    rename(IMAGE_FOLDER + \"\u002F\" + current, IMAGE_FOLDER + \"\u002F0_\" + current)\n    next_img()\n\n\nif __name__ == \"__main__\":\n\n    root = tk.Tk()\n\n    img_label = tk.Label(root)\n    img_label.pack()\n    img_label.bind(\"\u003CButton-1>\", positive)\n    img_label.bind(\"\u003CButton-3>\", negative)\n\n    btn = tk.Button(root, text='Next image', command=next_img)\n\n    next_img() # load first image\n\n    root.mainloop()\n```\n\n我们将所有未分类的图像加载到 \"unclassified_images\" 列表中，打开一个 tkinter 窗口，调用 next_img() 将第一张图像放入其中，并调整图像大小以适应屏幕。然后，我们注册两个点击事件，左键和右键鼠标按钮，并调用 positive\u002Fnegative 函数，根据标签重命名图像并显示下一张图像。\n\n虽然简陋但有效。\n\n## 步骤 5：开发预处理器以仅裁剪出图像中的人物\n\n对于下一步，我们需要将图像数据转换为允许我们进行分类的格式。鉴于我们的数据集，有一些困难需要考虑。\n\n1. **数据集大小：** 我们的数据集相对较小。我们有大约 2000 张图像，考虑到它们的复杂性（高分辨率 RGB（红、绿、蓝颜色模式）图像），这被认为是非常少的数据量。\n2. **数据差异：** 图片有时包含背面的人，有时只有脸，有时根本没有。\n3. **数据噪声：** 大多数图片不仅包含人物本身，还经常包含周围环境，这可能干扰我们的 AI（人工智能）。\n\n我们通过以下方式应对这些挑战：\n\n1. 将图像转换为灰度图 (greyscale)，以减少我们的 AI 需要学习的信息量（从 RGB 到 G，减少因子为 3）。\n2. 仅裁剪出图像中包含人物的部分，其他什么都不保留。\n\n![alt text](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_readme_79d629ba15d8.png)\n\n第一部分就像使用 Pillow（Python 图像处理库）打开图像并将其转换为灰度图一样简单。第二部分，我们使用 [Tensorflow Object Detection API](https:\u002F\u002Fgithub.com\u002Ftensorflow\u002Fmodels\u002Ftree\u002Fmaster\u002Fresearch\u002Fobject_detection)（TensorFlow 目标检测 API），采用 mobilenet（一种轻量级神经网络架构）网络架构，该架构在 coco 数据集（COCO 通用物体识别数据集）上进行了预训练，其中也包含“人物”标签。\n\n我们的人脸检测脚本分为四个部分：\n\n### 第一部分：将预训练的 mobilenet coco 数据集作为 Tensorflow 图打开\n\n你可以在我的 Github 仓库中找到 tensorflow mobilenet coco 图的 .pb 文件。让我们将其作为 Tensorflow 图打开：\n\n```python\nimport tensorflow as tf\n\ndef open_graph():\n    detection_graph = tf.Graph()\n    with detection_graph.as_default():\n        od_graph_def = tf.GraphDef()\n        with tf.gfile.GFile('ssd_mobilenet_v1_coco_2017_11_17\u002Ffrozen_inference_graph.pb', 'rb') as fid:\n            serialized_graph = fid.read()\n            od_graph_def.ParseFromString(serialized_graph)\n            tf.import_graph_def(od_graph_def, name='')\n    return detection_graph\n```\n\n### 第二部分：将图像加载为 numpy 数组\n\n我们使用 Pillow 进行图像处理。由于 tensorflow（深度学习框架）需要原始 numpy（Python 数值计算库）数组来处理数据，让我们编写一个小函数将 Pillow 图像转换为 numpy 数组：\n\n```python\nimport numpy as np\n\ndef load_image_into_numpy_array(image):\n    (im_width, im_height) = image.size\n    return np.array(image.getdata()).reshape(\n        (im_height, im_width, 3)).astype(np.uint8)\n```\n\n### 第 3 部分：调用目标检测 API（应用程序接口）\n\n下一个函数接收一张图像和一个 TensorFlow 计算图（graph），使用它运行一个 TensorFlow 会话（session），并返回所有关于检测到的类别（对象类型）、边界框（bounding boxes）和得分（scores）的信息（即物体被正确检测的置信度）。\n\n```python\nimport numpy as np\nfrom object_detection.utils import ops as utils_ops\nimport tensorflow as tf\n\ndef run_inference_for_single_image(image, sess):\n    ops = tf.get_default_graph().get_operations()\n    all_tensor_names = {output.name for op in ops for output in op.outputs}\n    tensor_dict = {}\n    for key in [\n        'num_detections', 'detection_boxes', 'detection_scores',\n        'detection_classes', 'detection_masks'\n    ]:\n        tensor_name = key + ':0'\n        if tensor_name in all_tensor_names:\n            tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(\n                tensor_name)\n    if 'detection_masks' in tensor_dict:\n        # The following processing is only for single image\n        detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\n        detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\n        # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n        real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\n        detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n        detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n        detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n            detection_masks, detection_boxes, image.shape[1], image.shape[2])\n        detection_masks_reframed = tf.cast(\n            tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n        # Follow the convention by adding back the batch dimension\n        tensor_dict['detection_masks'] = tf.expand_dims(\n            detection_masks_reframed, 0)\n    image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n    # Run inference\n    output_dict = sess.run(tensor_dict,\n                           feed_dict={image_tensor: image})\n\n    # all outputs are float32 numpy arrays, so convert types as appropriate\n    output_dict['num_detections'] = int(output_dict['num_detections'][0])\n    output_dict['detection_classes'] = output_dict[\n        'detection_classes'][0].astype(np.int64)\n    output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n    output_dict['detection_scores'] = output_dict['detection_scores'][0]\n    if 'detection_masks' in output_dict:\n        output_dict['detection_masks'] = output_dict['detection_masks'][0]\n    return output_dict\n```\n\n### 第 4 部分：整合所有内容以查找人物\n\n最后一步是编写一个函数，该函数接收图像路径，使用 Pillow（图像处理库）打开图像，调用目标检测 API（应用程序接口）接口，并根据检测到的人物的边界框对图像进行裁剪。\n\n```python\nimport numpy as np\nfrom PIL import Image\n\nPERSON_CLASS = 1\nSCORE_THRESHOLD = 0.5\n\ndef get_person(image_path, sess):\n    img = Image.open(image_path)\n    image_np = load_image_into_numpy_array(img)\n    image_np_expanded = np.expand_dims(image_np, axis=0)\n    output_dict = run_inference_for_single_image(image_np_expanded, sess)\n\n    persons_coordinates = []\n    for i in range(len(output_dict[\"detection_boxes\"])):\n        score = output_dict[\"detection_scores\"][i]\n        classtype = output_dict[\"detection_classes\"][i]\n        if score > SCORE_THRESHOLD and classtype == PERSON_CLASS:\n            persons_coordinates.append(output_dict[\"detection_boxes\"][i])\n\n    w, h = img.size\n    for person_coordinate in persons_coordinates:\n        cropped_img = img.crop((\n            int(w * person_coordinate[1]),\n            int(h * person_coordinate[0]),\n            int(w * person_coordinate[3]),\n            int(h * person_coordinate[2]),\n        ))\n        return cropped_img\n    return None\n```\n\n### 第 5 部分：将所有图像移动到相应的分类文件夹中\n\n作为最后一步，我们编写了一个脚本，该脚本遍历“未分类”文件夹中的所有图像，检查其文件名中是否包含编码标签，并在应用之前开发的预处理步骤后，将图像复制到相应的“已分类”文件夹中：\n\n```python\nimport os\nimport person_detector\nimport tensorflow as tf\n\nIMAGE_FOLDER = \".\u002Fimages\u002Funclassified\"\nPOS_FOLDER = \".\u002Fimages\u002Fclassified\u002Fpositive\"\nNEG_FOLDER = \".\u002Fimages\u002Fclassified\u002Fnegative\"\n\n\nif __name__ == \"__main__\":\n    detection_graph = person_detector.open_graph()\n\n    images = [f for f in os.listdir(IMAGE_FOLDER) if os.path.isfile(os.path.join(IMAGE_FOLDER, f))]\n    positive_images = filter(lambda image: (image.startswith(\"1_\")), images)\n    negative_images = filter(lambda image: (image.startswith(\"0_\")), images)\n\n    with detection_graph.as_default():\n        with tf.Session() as sess:\n\n            for pos in positive_images:\n                old_filename = IMAGE_FOLDER + \"\u002F\" + pos\n                new_filename = POS_FOLDER + \"\u002F\" + pos[:-5] + \".jpg\"\n                if not os.path.isfile(new_filename):\n                    img = person_detector.get_person(old_filename, sess)\n                    if not img:\n                        continue\n                    img = img.convert('L')\n                    img.save(new_filename, \"jpeg\")\n\n            for neg in negative_images:\n                old_filename = IMAGE_FOLDER + \"\u002F\" + neg\n                new_filename = NEG_FOLDER + \"\u002F\" + neg[:-5] + \".jpg\"\n                if not os.path.isfile(new_filename):\n                    img = person_detector.get_person(old_filename, sess)\n                    if not img:\n                        continue\n                    img = img.convert('L')\n                    img.save(new_filename, \"jpeg\")\n```\n\n每当运行此脚本时，所有带标签的图像都会被处理并移动到“已分类”目录中的相应子文件夹中。\n\n## 步骤 6：重新训练 inceptionv3 并编写 Classifier（分类器）\n\n对于重新训练部分，我们将直接使用 TensorFlow（TensorFlow 深度学习框架）的 [retrain.py](https:\u002F\u002Fgithub.com\u002Ftensorflow\u002Fhub\u002Fblob\u002Fmaster\u002Fexamples\u002Fimage_retraining\u002Fretrain.py) 脚本配合 inceptionv3 模型。\n\n在您的项目根目录下调用该脚本，参数如下：\n\n```shell\npython retrain.py --bottleneck_dir=tf\u002Ftraining_data\u002Fbottlenecks --model_dir=tf\u002Ftraining_data\u002Finception --summaries_dir=tf\u002Ftraining_data\u002Fsummaries\u002Fbasic --output_graph=tf\u002Ftraining_output\u002Fretrained_graph.pb --output_labels=tf\u002Ftraining_output\u002Fretrained_labels.txt --image_dir=.\u002Fimages\u002Fclassified --how_many_training_steps=50000 --testing_percentage=20 --learning_rate=0.001\n```\n\n在 GTX 1080 Ti 上，学习过程大约需要 15 分钟，对于我的标记数据集，最终准确率约为 80%，但这很大程度上取决于您输入数据的质量和标注情况。 \n\n训练过程的结果是在 \"tf\u002Ftraining_output\u002Fretrained_graph.pb\" 文件中的重新训练的 inceptionV3 模型。我们现在必须编写一个 Classifier（分类器）类，该类能高效地利用 TensorFlow 图中的新 weights（权重）来进行分类预测。 \n\n让我们编写一个 Classifier（分类器）类，它将 graph（计算图）作为 session（会话）打开，并提供一个 \"classify\" 方法，该方法接收图像文件，返回一个包含与我们 labels（标签）\"positive\"（正例）和 \"negative\"（负例）匹配的置信度值的 dict（字典）。\n\n该类接收图的 path（路径）以及标签文件的 path（路径）作为输入，两者都位于我们的 \"tf\u002Ftraining_output\u002F\" 文件夹中。我们开发了辅助函数，用于将图像文件转换为可以馈送到我们 graph（计算图）中的 tensor（张量），一个用于加载 graph（计算图）和 labels（标签）的辅助函数，以及一个在我们使用完毕后关闭 graph（计算图）的重要小函数。 \n```python\nimport numpy as np\nimport tensorflow as tf\n\nclass Classifier():\n    def __init__(self, graph, labels):\n\n        self._graph = self.load_graph(graph)\n        self._labels = self.load_labels(labels)\n\n        self._input_operation = self._graph.get_operation_by_name(\"import\u002FPlaceholder\")\n        self._output_operation = self._graph.get_operation_by_name(\"import\u002Ffinal_result\")\n\n        self._session = tf.Session(graph=self._graph)\n\n    def classify(self, file_name):\n        t = self.read_tensor_from_image_file(file_name)\n\n        # Open up a new tensorflow session and run it on the input\n        results = self._session.run(self._output_operation.outputs[0], {self._input_operation.outputs[0]: t})\n        results = np.squeeze(results)\n\n        # Sort the output predictions by prediction accuracy\n        top_k = results.argsort()[-5:][::-1]\n\n        result = {}\n        for i in top_k:\n            result[self._labels[i]] = results[i]\n\n        # Return sorted result tuples\n        return result\n\n    def close(self):\n        self._session.close()\n\n\n    @staticmethod\n    def load_graph(model_file):\n        graph = tf.Graph()\n        graph_def = tf.GraphDef()\n        with open(model_file, \"rb\") as f:\n            graph_def.ParseFromString(f.read())\n        with graph.as_default():\n            tf.import_graph_def(graph_def)\n        return graph\n\n    @staticmethod\n    def load_labels(label_file):\n        label = []\n        proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()\n        for l in proto_as_ascii_lines:\n            label.append(l.rstrip())\n        return label\n\n    @staticmethod\n    def read_tensor_from_image_file(file_name,\n                                    input_height=299,\n                                    input_width=299,\n                                    input_mean=0,\n                                    input_std=255):\n        input_name = \"file_reader\"\n        file_reader = tf.read_file(file_name, input_name)\n        image_reader = tf.image.decode_jpeg(\n            file_reader, channels=3, name=\"jpeg_reader\")\n        float_caster = tf.cast(image_reader, tf.float32)\n        dims_expander = tf.expand_dims(float_caster, 0)\n        resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])\n        normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])\n        sess = tf.Session()\n        result = sess.run(normalized)\n        return result\n```\n\n## 步骤 7：利用这些内容实际自动玩 Tinder\n\n既然我们已经有了 Classifier（分类器），让我们扩展之前提到的 \"Person\"（人物）类，并为其添加一个 \"predict_likeliness\"（预测喜好可能性）函数，该函数使用 Classifier（分类器）实例来验证是否应该喜欢给定的人。\n\n```python\n\n# 在 Person 类中\n\n```python\n    def predict_likeliness(self, classifier, sess):\n        ratings = []\n        for image in self.images:\n            req = requests.get(image, stream=True)\n            tmp_filename = f\".\u002Fimages\u002Ftmp\u002Frun.jpg\"\n            if req.status_code == 200:\n                with open(tmp_filename, \"wb\") as f:\n                    f.write(req.content)\n            img = person_detector.get_person(tmp_filename, sess)\n            if img:\n                img = img.convert('L')\n                img.save(tmp_filename, \"jpeg\")\n                certainty = classifier.classify(tmp_filename)\n                pos = certainty[\"positive\"]\n                ratings.append(pos)\n        ratings.sort(reverse=True)\n        ratings = ratings[:5]\n        if len(ratings) == 0:\n            return 0.001\n        return ratings[0]*0.6 + sum(ratings[1:])\u002Flen(ratings[1:])*0.4\n```\n\n现在我们需要将所有拼图碎片组合在一起。 \n\n首先，让我们使用我们的 API 令牌初始化 Tinder API（应用程序编程接口）。然后，我们使用重新训练的图和标签，将分类 TensorFlow（一种开源机器学习框架）图打开为 TensorFlow 会话。接着，我们获取附近的人并进行 Likelihood（可能性）预测。 \n\n作为额外奖励，如果 Tinder 上的人在和我相同的大学就读，我添加了一个 1.2 的 Likelihood（可能性）乘数，这样我更有可能与本地学生匹配。 \n\n对于所有预测 Likelihood（可能性）分数为 0.8 的人，我执行“喜欢”操作，对于其他人则执行“不喜欢”操作。\n\n我开发了这个脚本，使其在启动后自动运行接下来的 2 小时。\n\n```python\nfrom likeliness_classifier import Classifier\nimport person_detector\nimport tensorflow as tf\nfrom time import time\n\nif __name__ == \"__main__\":\n    token = \"YOUR-API-TOKEN\"\n    api = tinderAPI(token)\n\n    detection_graph = person_detector.open_graph()\n    with detection_graph.as_default():\n        with tf.Session() as sess:\n\n            classifier = Classifier(graph=\".\u002Ftf\u002Ftraining_output\u002Fretrained_graph.pb\",\n                                    labels=\".\u002Ftf\u002Ftraining_output\u002Fretrained_labels.txt\")\n\n            end_time = time() + 60*60*2\n            while time() \u003C end_time:\n                try:\n                    persons = api.nearby_persons()\n                    pos_schools = [\"Universität Zürich\", \"University of Zurich\", \"UZH\"]\n\n                    for person in persons:\n                        score = person.predict_likeliness(classifier, sess)\n\n                        for school in pos_schools:\n                            if school in person.schools:\n                                print()\n                                score *= 1.2\n\n                        print(\"-------------------------\")\n                        print(\"ID: \", person.id)\n                        print(\"Name: \", person.name)\n                        print(\"Schools: \", person.schools)\n                        print(\"Images: \", person.images)\n                        print(score)\n\n                        if score > 0.8:\n                            res = person.like()\n                            print(\"LIKE\")\n                        else:\n                            res = person.dislike()\n                            print(\"DISLIKE\")\n                except Exception:\n                    pass\n\n    classifier.close()\n```\n\n就是这样！我们现在可以让脚本运行任意长时间，并且在不滥用拇指的情况下玩 Tinder！\n\n如果您有问题或发现了错误，欢迎贡献到我的 [Github 仓库](https:\u002F\u002Fgithub.com\u002FjoelbarmettlerUZH\u002Fauto-tinder)。\n\n# 许可证\nMIT 许可证\n\nCopyright (c) 2018 Joel Barmettler\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\u002For sell \ncopies of the Software, and to permit persons to whom the Software is furnished \nto do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in \nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS \nOR IMPLIED, 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\n顺便提一下，我是来自苏黎世的 [AI（人工智能）工程师](https:\u002F\u002Fjoelbarmettler.xyz\u002F)，从事 [AI 研究](https:\u002F\u002Fjoelbarmettler.xyz\u002Fresearch\u002F)，并在瑞士苏黎世担任 [AI 主题演讲嘉宾](https:\u002F\u002Fjoelbarmettler.xyz\u002Fauftritte\u002F) 和举办 [AI 网络研讨会](https:\u002F\u002Fjoelbarmettler.xyz\u002Fauftritte\u002Fwebinar-2024-rewind-2025-ausblick\u002F)！","# Auto-Tinder 快速上手指南\n\n> **⚠️ 重要免责声明**\n> Auto-Tinder 是一个纯概念项目，仅供娱乐和教育目的。该脚本**违反 Tinder 的服务条款（Terms of Service）**，可能导致账号被封禁。请勿在真实 Tinder 账号上使用此工具，切勿滥用以伤害他人或骚扰平台。\n\n## 1. 环境准备\n\n本项目基于 Python 3 开发，依赖 TensorFlow 进行图像识别。\n\n- **操作系统**: Windows \u002F macOS \u002F Linux\n- **编程语言**: Python 3.x\n- **网络要求**: 需能访问 Tinder 后端 API (`api.gotinder.com`) 及 Google Images CDN。\n- **前置依赖**:\n  - `requests`: 用于 HTTP 请求\n  - `geopy`: 用于地理位置解析\n  - `tensorflow`: 用于深度学习模型推理\n  - `opencv-python` (建议): 用于图像处理（参考文档提及 Object Detection）\n\n## 2. 安装步骤\n\n### 2.1 克隆项目\n建议使用国内镜像加速下载：\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FjoelbarmettlerUZH\u002Fauto-tinder.git\ncd auto-tinder\n```\n\n### 2.2 安装依赖\n根据项目代码中的导入语句，安装必要的 Python 库：\n\n```bash\npip install requests geopy tensorflow opencv-python\n```\n\n### 2.3 获取认证令牌 (Auth Token)\n这是运行脚本的关键步骤。你需要从浏览器开发者工具中获取你的 `X-Auth-Token`。\n\n1. 打开 [tinder.com](https:\u002F\u002Ftinder.com) 并登录。\n2. 按 `F12` 打开开发者工具，切换到 **Network** 标签页。\n3. 刷新页面，查找请求头中包含 `X-Auth-Token` 的请求。\n4. 复制该 Token 值，后续将在代码中配置使用。\n\n## 3. 基本使用\n\n项目核心逻辑包含一个 API 包装类和一个用户对象类。以下是基于 README 提供的核心代码结构示例。\n\n### 3.1 初始化 API 接口\n使用 `tinderAPI` 类封装与 Tinder 后端的交互：\n\n```python\nimport requests\n\nTINDER_URL = \"https:\u002F\u002Fapi.gotinder.com\"\n\nclass tinderAPI():\n\n    def __init__(self, token):\n        self._token = token\n\n    def profile(self):\n        data = requests.get(TINDER_URL + \"\u002Fv2\u002Fprofile?include=account%2Cuser\", headers={\"X-Auth-Token\": self._token}).json()\n        return Profile(data[\"data\"], self)\n\n    def matches(self, limit=10):\n        data = requests.get(TINDER_URL + f\"\u002Fv2\u002Fmatches?count={limit}\", headers={\"X-Auth-Token\": self._token}).json()\n        return list(map(lambda match: Person(match[\"person\"], self), data[\"data\"][\"matches\"]))\n\n    def like(self, user_id):\n        data = requests.get(TINDER_URL + f\"\u002Flike\u002F{user_id}\", headers={\"X-Auth-Token\": self._token}).json()\n        return {\n            \"is_match\": data[\"match\"],\n            \"liked_remaining\": data[\"likes_remaining\"]\n        }\n\n    def dislike(self, user_id):\n        requests.get(TINDER_URL + f\"\u002Fpass\u002F{user_id}\", headers={\"X-Auth-Token\": self._token}).json()\n        return True\n\n    def nearby_\n```\n\n### 3.2 处理用户数据\n`Person` 类用于解析 API 返回的 JSON 数据，并提供简单的点赞\u002F跳过接口：\n\n```python\nimport datetime\nfrom geopy.geocoders import Nominatim\n\nTINDER_URL = \"https:\u002F\u002Fapi.gotinder.com\"\ngeolocator = Nominatim(user_agent=\"auto-tinder\")\nPROF_FILE = \".\u002Fimages\u002Funclassified\u002Fprofiles.txt\"\n\nclass Person(object):\n\n    def __init__(self, data, api):\n        self._api = api\n\n        self.id = data[\"_id\"]\n        self.name = data.get(\"name\", \"Unknown\")\n\n        self.bio = data.get(\"bio\", \"\")\n        self.distance = data.get(\"distance_mi\", 0) \u002F 1.60934\n\n        self.birth_date = datetime.datetime.strptime(data[\"birth_date\"], '%Y-%m-%dT%H:%M:%S.%fZ') if data.get(\n            \"birth_date\", False) else None\n        self.gender = [\"Male\", \"Female\", \"Unknown\"][data.get(\"gender\", 2)]\n\n        self.images = list(map(lambda photo: photo[\"url\"], data.get(\"photos\", [])))\n\n        self.jobs = list(\n            map(lambda job: {\"title\": job.get(\"title\", {}).get(\"name\"), \"company\": job.get(\"company\", {}).get(\"name\")}, data.get(\"jobs\", [])))\n        self.schools = list(map(lambda school: school[\"name\"], data.get(\"schools\", [])))\n\n        if data.get(\"pos\", False):\n            self.location = geolocator.reverse(f'{data[\"pos\"][\"lat\"]}, {data[\"pos\"][\"lon\"]}')\n\n\n    def __repr__(self):\n        return f\"{self.id}  -  {self.name} ({self.birth_date.strftime('%d.%m.%Y')})\"\n\n\n    def like(self):\n        return self._api.like(self.id)\n\n    def dislike(self):\n        return self._api.dislike(self.id)\n```\n\n### 3.3 运行流程\n1. **获取推荐列表**: 调用 `tinderAPI` 获取附近的用户数据。\n2. **图像预处理**: 使用 TensorFlow Object Detection API 裁剪出人物主体。\n3. **模型推理**: 加载训练好的 InceptionV3 模型对图片进行分类（喜欢\u002F不喜欢）。\n4. **执行操作**: 根据分类结果调用 `Person.like()` 或 `Person.dislike()`。\n\n> **注意**: 由于原始 README 内容截断，完整的项目实现需要开发者自行补充剩余的训练数据和主循环逻辑。","某位生活在一线城市的资深程序员，工作繁忙且对技术充满好奇。他希望能找到能理解自己偏好的伴侣，但苦于没有时间精力。\n\n### 没有 auto-tinder 时\n- 每天通勤路上需手动滑动数百次，消耗大量宝贵休息时间且易产生视觉疲劳\n- 纯凭直觉判断颜值与兴趣，缺乏客观标准导致匹配质量参差不齐，浪费情感投入\n- 难以从海量图片中快速定位目标人物，容易错过合适人选或陷入无效信息过载\n- 反复查看相同类型的资料，无法建立稳定的筛选逻辑，导致决策效率低下\n\n### 使用 auto-tinder 后\n- 利用 Python 构建 API 包装类，自动模拟登录并执行点赞或跳过指令，解放双手\n- 通过 TensorFlow 重训 Inceptionv3 网络，让 AI 精准学习个人审美偏好，越用越懂你\n- 结合物体检测 API 预处理图像，只截取人物主体进行高效分类，减少背景干扰\n- 系统全天候自动运行，将原本需要数小时的筛选工作压缩至几分钟完成，专注生活\n\n核心价值在于将主观的择偶决策转化为可量化的自动化流程，极大提升了筛选效率与准确性。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FjoelbarmettlerUZH_auto-tinder_78c815cb.png","joelbarmettlerUZH","Joel Barmettler","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FjoelbarmettlerUZH_8b6529fa.jpg","M. Sc. Artificial Intelligence \r\n& Senior A.I. Architect","bbv","Zurich, Switzerland",null,"https:\u002F\u002Fjoelbarmettler.xyz","https:\u002F\u002Fgithub.com\u002FjoelbarmettlerUZH",[85],{"name":86,"color":87,"percentage":88},"Python","#3572A5",100,565,90,"2026-04-01T17:10:46","MIT","未说明",{"notes":95,"python":96,"dependencies":97},"项目仅用于教育和娱乐目的；明确警告违反 Tinder 服务条款，切勿用于真实账号；需自行标注图片数据并训练 InceptionV3 模型；依赖 TensorFlow Object Detection API 进行图像预处理。","Python3",[98,99,100],"tensorflow","requests","geopy",[26,14,54,13,53,15],[103,104,105,106,98,107,108],"tinder","tinder-bot","tinder-api","object-detection-api","ai","bot","2026-03-27T02:49:30.150509","2026-04-06T08:46:18.588827",[112,117],{"id":113,"question_zh":114,"answer_zh":115,"source_url":116},2080,"系统要求是什么？是否需要 GPU 还是可以在 CPU 上运行？如果遇到 `AttributeError: module 'tensorflow' has no attribute 'GraphDef'` 错误该怎么办？","关于 TensorFlow 报错问题，这通常是因为使用了 TensorFlow 2 版本导致的兼容性问题。请将代码中的 `tf.GraphDef()` 修改为 `tf.compat.v1.GraphDef()`，并将 `tf.gfile.GFile()` 修改为 `tf.compat.v2.io.gfile.GFile()`。关于系统要求和 GPU\u002FCPU 的具体配置，评论区暂未提供详细信息。","https:\u002F\u002Fgithub.com\u002FjoelbarmettlerUZH\u002Fauto-tinder\u002Fissues\u002F9",{"id":118,"question_zh":119,"answer_zh":120,"source_url":121},2081,"能否将同一用户的图片作为一组下载？如果同一人的照片被模型同时标记为喜欢和不喜欢，模型如何分类？","目前该问题在评论区暂无维护者或其他用户提供具体的解决方案或配置方法。建议检查代码中 `download_images()` 函数的逻辑以确认分组机制，或关注项目后续更新。","https:\u002F\u002Fgithub.com\u002FjoelbarmettlerUZH\u002Fauto-tinder\u002Fissues\u002F2",[]]