-
Notifications
You must be signed in to change notification settings - Fork 8.2k
bump version to 0.1.13 #333
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+2
−2
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Codecov Report
@@ Coverage Diff @@
## main #333 +/- ##
=======================================
Coverage 42.33% 42.33%
=======================================
Files 19 19
Lines 2393 2393
Branches 539 539
=======================================
Hits 1013 1013
Misses 1302 1302
Partials 78 78
Flags with carried forward coverage won't be shown. Click here to find out more.
|
pcdeadeasy
approved these changes
Oct 21, 2023
jfischburg-us
added a commit
to jfischburg-us/autogen
that referenced
this pull request
Nov 12, 2023
* Improves clarity and fixes punctuation in README and Multi-agent documentation (microsoft#40) * Improves clarity and fixes punctuation in README and Multi-agent documentation * fix broken colab link to agentchat_groupchat_research.ipynb (others are fine) * fix typos, improves readability * make retry_time configurable, add doc (microsoft#53) * make retry_time configurable, add doc * in seconds * retry_wait_time * bump version to 0.1.4 * remove .json * rename * time * Update no_update_context, fix upsert docs (microsoft#52) * Update no_update_context, fix upsert docs * Recreate only once * Add comments to get_or_create --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update README.md (microsoft#54) README update for my profile <3 * retrieve_utils.py - Updated.py to have the ability to parse text from PDF Files (microsoft#50) * UPDATE - Updated retrieve_utils.py to have the ability to parse text from pdf files * UNDO - change to recursive condition * UPDATE - updated agentchat_RetrieveChat.ipynb to clarify which file types are accepted to be in the docs path * ADD - missing import * UPDATE - setup.py to have PyPDF2 in retrievechat * RE-ADD - urls * ADD - tests for retrieve utils, and removed deprecated PyPdf2 * Update agentchat_RetrieveChat.ipynb * Update retrieve_utils.py Fix format * Update retrieve_utils.py Replace print with logger * UPDATE - added more specific exception to PDF decryption try/catch * FIX - typo, return statement at wrong indentation in extract_text_from_pdf --------- Co-authored-by: Ward <award40@LAMU0CLP74YXVX6.uhc.com> Co-authored-by: Li Jiang <bnujli@gmail.com> * Bump version to 0.1.5 (microsoft#60) * typing & docstr update (microsoft#59) * typing & docstr update * bump version to 0.1.5 * Updated readme.md : seprated AutoGen and EcoOptGen also removed bibtex (microsoft#43) * Updated README.md added required changes to previous pull new changes : 1. A section containing citation to AutoGen and EcoOptiGen 2. Another section contain citation to MathChat ## Citation [AutoGen](https://arxiv.org/abs/2308.08155). AND [EcoOptiGen](https://arxiv.org/abs/2303.04673). ``` bibtex @inproceedings{wu2023autogen, title={AutoGen: Enabling Next-Gen LLM Applications via Multi-Agent Conversation Framework}, author={Qingyun Wu and Gagan Bansal and Jieyu Zhang and Yiran Wu and Shaokun Zhang and Erkang Zhu and Beibin Li and Li Jiang and Xiaoyun Zhang and Chi Wang}, year={2023}, eprint={2308.08155}, archivePrefix={arXiv}, primaryClass={cs.AI} } bibtex @inproceedings{wang2023EcoOptiGen, title={Cost-Effective Hyperparameter Optimization for Large Language Model Generation Inference}, author={Chi Wang and Susan Xueqing Liu and Ahmed H. Awadallah}, year={2023}, booktitle={AutoML'23}, } ``` [MathChat](https://arxiv.org/abs/2306.01337). ``` bibtex @inproceedings{wu2023empirical, title={An Empirical Study on Challenging Math Problem Solving with GPT-4}, author={Yiran Wu and Feiran Jia and Shaokun Zhang and Hangyu Li and Erkang Zhu and Yue Wang and Yin Tat Lee and Richard Peng and Qingyun Wu and Chi Wang}, year={2023}, booktitle={ArXiv preprint arXiv:2306.01337}, } ``` * Seperated AutoGen and EcoOptGen and removed 'bibtex' ## Citation [AutoGen](https://arxiv.org/abs/2308.08155). ``` @inproceedings{wu2023autogen, title={AutoGen: Enabling Next-Gen LLM Applications via Multi-Agent Conversation Framework}, author={Qingyun Wu and Gagan Bansal and Jieyu Zhang and Yiran Wu and Shaokun Zhang and Erkang Zhu and Beibin Li and Li Jiang and Xiaoyun Zhang and Chi Wang}, year={2023}, eprint={2308.08155}, archivePrefix={arXiv}, primaryClass={cs.AI} } ``` [EcoOptiGen](https://arxiv.org/abs/2303.04673). ``` @inproceedings{wang2023EcoOptiGen, title={Cost-Effective Hyperparameter Optimization for Large Language Model Generation Inference}, author={Chi Wang and Susan Xueqing Liu and Ahmed H. Awadallah}, year={2023}, booktitle={AutoML'23}, } ``` * expand faq (microsoft#66) * expand faq * models * fix format error * minor fix (microsoft#31) * minor fix for stablility * fix format * fix format * update run_code logic * format * Update conversable_agent.py * fix format * Update conversable_agent.py * add tests * fix format * revert changes * Fixed MD Issue (microsoft#72) * fix append_oai_message (microsoft#47) * fix append_oai_message * add testcase for groupchat * add test_oai to openai workflow * code formate * update * formate * update * enable openai workflow on fork branch (microsoft#82) * update * update * Update openai.yml * bump version to 0.1.6 (microsoft#85) * spelling error (microsoft#84) * Format issue (microsoft#69) * Fixed formating issue in the README * Fixed the formating issue in the README * Updated formatting as per review comments * Refactor README.md to highlight use cases and features * Updated README as per feedback * Updated README as per feedback --------- Co-authored-by: Al-Iqram Elahee <hridoy@Al-Iqrams-MacBook-Pro.local> Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Replace the use of `assert` in non-test code (microsoft#80) * Replace `assert`s in the `conversable_agent` module with `if-log-raise`. * Use a `logger` object in the `code_utils` module. * Replace use of `assert` with `if-log-raise` in the `code_utils` module. * Replace use of `assert` in the `math_utils` module with `if-not-raise`. * Replace `assert` with `if` in the `oai.completion` module. * Replace `assert` in the `retrieve_utils` module with an if statement. * Add missing `not`. * Blacken `completion.py`. * Test `generate_reply` and `a_generate_reply` raise an assertion error when there are neither `messages` nor a `sender`. * Test `execute_code` raises an `AssertionError` when neither code nor filename is provided. * Test `split_text_to_chunks` raises when passed an invalid chunk mode. * * Add `tiktoken` and `chromadb` to test dependencies as they're used in the `test_retrieve_utils` module. * Sort the test requirements alphabetically. * Bump postcss from 8.4.18 to 8.4.31 in /website (microsoft#93) Bumps [postcss](https://github.com/postcss/postcss) from 8.4.18 to 8.4.31. - [Release notes](https://github.com/postcss/postcss/releases) - [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md) - [Commits](postcss/postcss@8.4.18...8.4.31) --- updated-dependencies: - dependency-name: postcss dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * show github stars (microsoft#92) * Docs: fixed typos and grammar (microsoft#94) * openai_utils.py - functionality for instantiating config_list with a .env file (microsoft#68) * FORMATTING * UPDATE - OAI __init__.py * ruff * ADD - notebook covering oai API configuration options and their different purposes * ADD openai util updates so that the function just assumes the same environment variable name for all models, also added functionality for adding API configurations like api_base etc. * ADD - updates to config_list_from_dotenv and tests for openai_util testing, update example notebook * UPDATE - added working config_list_from_dotenv() with passing tests, and updated notebook * UPDATE - code and tests to potentially get around the window build permission error, used different method of producing temporary files --------- Co-authored-by: Ward <award40@LAMU0CLP74YXVX6.uhc.com> * document about docker (microsoft#119) * document about docker * clarify * dev container * docs: typo fixed (microsoft#129) * Fix broken link in README.md (microsoft#134) The link to the documentation's FAQ#code-execution was broken because the 'docs' directory was missing in the original URL. Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * fix doc typo (microsoft#123) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * typo fixed (microsoft#127) Co-authored-by: Sagar Desai <60027013+sagardesai-ml-mlops@users.noreply.github.com> Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * bump version to 0.1.7 (microsoft#141) * Title: Adjust shell language switch in execute_code for Docker usage (microsoft#139) Description: This commit modifies the conditional check in execute_code to ensure the switch to PowerShell on Windows only occurs when Docker is not being used. This keeps shell script execution consistent within a Docker container across all platforms, aligning with the function's intended behavior. Co-authored-by: Xiaoyun Zhang <bigmiao.zhang@gmail.com> * move citation before contributing (microsoft#154) * bump version to 0.1.8 * add twitter account to website (microsoft#150) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update num tokens from text (microsoft#149) * Improve num_tokens_from_text * Format * Update comments * Improve docstrings * add twitter account to start page (microsoft#159) * Update termination logic (microsoft#155) * Added twitter link to the contributing section (microsoft#162) Co-authored-by: vidhula17 <catchvidhula@gmail.com> * fix: replace gpt-35-turbo in model name to gpt-3.5-turbo so the name … (microsoft#138) * fix: replace gpt-35-turbo in model name to gpt-3.5-turbo so the name string is in the current chat_model list * ref: reformatted with black --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Output a warning if attempting to load the OAI_CONFIG_LIST from a file, but the file is not found. (microsoft#174) * Warn if GroupChat is underpopulatd. (microsoft#170) * Display a warning if use_docker evlauates to True but the python docker package is not available. (microsoft#172) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * bump version to 0.1.9 (microsoft#177) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Warn if oai.Completion is provided with an empty config_list (microsoft#178) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Bump version to 0.1.10 (microsoft#181) * Add support to customized vectordb and embedding functions (microsoft#161) * Add custom embedding function * Add support to custom vector db * Improve docstring * Improve docstring * Improve docstring * Add support to customized is_termination_msg fucntion * Add a test for customize vector db with lancedb * Fix tests * Add test for embedding_function * Update docstring * Fix typo in agentchat_MathChat.ipynb (microsoft#191) requries -> requires * Make getting started a little easier (microsoft#180) * Update README.md add codespace quick start * add codespace * update path --------- Co-authored-by: Li Jiang <lijiang1@microsoft.com> * Fix edge cases extracting code when the message's content is None (microsoft#205) * Add md for faqs (microsoft#194) * Add md for faq; Update readme * Update TRANSPARENCY_FAQS.md Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update TRANSPARENCY_FAQS.md Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Remove trailing space * Fix trailing space issue --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Fix typo in README.md (microsoft#193) * Icons not centered in the "autogen_agentchat.png" (microsoft#169) * Delete website/static/img/autogen_agentchat.png * Add files via upload * Addresses issue microsoft#199 (microsoft#200) * Addresses issue microsoft#199 * Fixed comment to align with new behavior. --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Improving logging in oai.completion to show token_count (microsoft#179) * update * update doc --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Update Getting-Started.md (microsoft#213) Fixed minor typo Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Added comment about config_list in the README example microsoft#216 (microsoft#218) * Update README.md * Update README.md * fix: be compatible with custom model without full response (microsoft#222) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Update Installation.md-with detailed explanation on add a period or newline microsoft#219 (microsoft#231) * Update Installation.md Usage and importance of Docker is explained in more precise and to the point * Update website/docs/Installation.md --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Spelling fixes. (microsoft#220) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Typo (microsoft#234) * fix typo * wording * typo * bump version to 0.1.11 (microsoft#242) * bump version to 0.1.11 * fix format issue * docstr updated for `use_docker` in `execute_code ` (microsoft#233) * docstr updated * fixed line 245 * Fixed line 246 * space_traling error Fix_01 * Revert space in '-' * Fixed line 245 FIX_02 --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * document retrieve chat (microsoft#258) * document retrieve chat * Ran pre commit hook * Added figure to notebook (microsoft#246) Co-authored-by: Li Jiang <lijiang1@microsoft.com> * Lancgain tool bridge (microsoft#262) (microsoft#263) * Added a LangChain tooling bridge example * Updated Doco * Update agentchat_langchain.ipynb remove key --------- Co-authored-by: Elliot Wood <gigaflare_elliot@hotmail.com> Co-authored-by: Li Jiang <lijiang1@microsoft.com> * Add support to custom text spliter (microsoft#270) * Add support to custom text spliter function and a list of files or urls * Add parameter to retrieve_config, add tests * Fix tests * Fix tests * Update FAQ.md, elaborate on how to customise docker image and pick 'python:3' to solve typical errors (microsoft#269) * Update FAQ.md * Update website/docs/FAQ.md Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Update website/docs/FAQ.md Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Update website/docs/FAQ.md Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Add group chat and retrieve agent example (microsoft#227) * Add group chat and retrieve agent example * Fix link and models * Support call rag in a group chat and not init with rag * Fix n_results logic * Update notebook * Fix format * Improve wording * Update variable name * Revert to main * Update function call * Update keys * Update contents * Update contents * docs: added virtual environment setup process (microsoft#249) * docs: added virtual environment setup process * Update website/docs/Installation.md --------- Co-authored-by: Li Jiang <bnujli@gmail.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update Getting-Started.md (microsoft#275) Co-authored-by: Li Jiang <bnujli@gmail.com> Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Bump @babel/traverse from 7.20.1 to 7.23.2 in /website (microsoft#283) Bumps [@babel/traverse](https://github.com/babel/babel/tree/HEAD/packages/babel-traverse) from 7.20.1 to 7.23.2. - [Release notes](https://github.com/babel/babel/releases) - [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md) - [Commits](https://github.com/babel/babel/commits/v7.23.2/packages/babel-traverse) --- updated-dependencies: - dependency-name: "@babel/traverse" dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Add a blog for RAG agents (microsoft#284) * Init blog * Update blog * Add more contents * Restore notebook * function call filter in group chat (microsoft#294) * function call filter in group chat * find agents with function_map * fix typo in website/blog/2023-05-18-GPT-adaptive-humaneval/index.mdx (microsoft#299) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Organize notebooks into logical groups microsoft#273 (microsoft#288) * Organize notebooks into logical groups microsoft#273 * update multiagent group to mention >3 agents * Update docs (microsoft#297) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Update README.md with Roadmap. (microsoft#304) also removed ugly periods. fixes: microsoft#289 (comment) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * bump version to 0.1.12 (microsoft#301) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * doc: Update FAQ.md (microsoft#282) Isssue microsoft#277 * Fix format and links in documentations (microsoft#310) * Fix format and links * Update title * Sync title * Add examples to installation * update oai models (microsoft#316) * guidance for contribution (microsoft#320) * TeachableAgent (microsoft#278) * Initial commit. * Disable LLM response caching. * Add teachability option to setup.py * Modify test to use OAI_CONFIG_LIST as suggested in the docs. * Expand unit test. * Complete unit test. * Add filter_dict * details * AnalysisAgent * details * More documentation and debug output. * Support retrieval of any number of relevant memos, including zero. * More robust analysis separator. * cleanup * teach_config * refactoring * For robustness, allow more flexibility on memo storage and retrieval. * de-dupe the retrieved memos. * Simplify AnalysisAgent. The unit tests now pass with gpt-3.5 * comments * Add a verbosity level to control analyzer messages. * refactoring * comments * Persist memory on disk. * cleanup * Use markdown to format retrieved memos. * Use markdown in TextAnalyzerAgent * Add another verbosity level. * clean up logging * notebook * minor edits * cleanup * linter fixes * Skip tests that fail to import openai * Address reviewer feedback. * lint * refactoring * Improve wording * Improve code coverage. * lint * Use llm_config to control caching. * lowercase notebook name * Sort out the parameters passed through to ConversableAgent, and supply full docstrings for the others. * lint * Allow TextAnalyzerAgent to be given a different llm_config than TeachableAgent. * documentation * Modifications to run openai workflow. * Test on just python 3.10. Replace agent with agent teachable_agent as recommended. * Test on python 3.9 instead of 3.10. * Remove space from name -> teachableagent --------- Co-authored-by: Li Jiang <bnujli@gmail.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com> * bump version to 0.1.13 (microsoft#333) * add downloads stats in readme (microsoft#334) * Added Roadmap to Getting-Started.md (microsoft#324) * Resolves Typo Correction microsoft#336 (microsoft#338) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update README.md (microsoft#321) Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Updating Examples to follow new categorical structure. microsoft#273 (microsoft#327) * Updating Examples to follow new categorical structure. microsoft#273 Addressing the remaining task for microsoft#273, I have copied over the changes from /Usecases to /Examples to follow the new categorical example notebooks structure. * Add the new example notebook --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> * Update agentchat_auto_feedback_from_code_execution.ipynb (microsoft#342) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update agentchat_MathChat.ipynb (microsoft#341) * Fix grammar and spelling in agentchat_chess.ipynb (microsoft#346) * Improve readability for agentchat_function_call.ipynb (microsoft#347) * Improve readability in agentchat_groupchat_research.ipynb (microsoft#350) * Improve readability in agentchat_groupchat_research.ipynb * Undo updates to system message. * format (microsoft#358) * Improve readability in oai_openai_utils.ipynb (microsoft#365) * Improve readability in oai_completion.ipynb (microsoft#364) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Fix grammar for agentchat_web_info.ipynb (microsoft#362) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Improve readability for agentchat_two_users.ipynb (microsoft#361) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Fix grammar in agentchat_stream.ipynb (microsoft#357) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Fix grammar and spelling in agentchat_planning.ipynb (microsoft#356) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Fix the grammar and spelling in agentchat_human_feedback.ipynb (microsoft#354) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update agentchat_langchain.ipynb (microsoft#355) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * headsup about dependency change (microsoft#378) * headsup about dependency change * more change * Add link to OptiGuide microsoft#371 (microsoft#376) * OptiGuide Link * Update AutoGen-AgentChat.md * fixes * Update docs in RetrieveChat notebook and Installation (microsoft#379) * Update comments to make it more clear * Update Installation * config list for test (microsoft#395) * Supporting MultiModal Models: an example with LLaVA Notebook (microsoft#286) * LMM notebook * Use "register_reply" instead. * Loop check LLaVA non-empty response * Run notebook * Make the llava_call function more flexible * Include API for LLaVA from Replicate * LLaVA data format update x2 1. prompt formater function 2. conversation format with SEP * Coding example added * Rename "ImageAgent" -> "LLaVAAgent" * Docstring and comments updates * Debug notebook: Remote LLaVA tested * Example 1: remove system message * MultimodalConversableAgent added * Add gpt4v_formatter * LLaVA: update example 1 * LLaVA: Add link to "Table of Content" * using thread safe timeout to allow code execution to be compatible with multi-threading/multi-processing (microsoft#224) Co-authored-by: Li Jiang <lijiang1@microsoft.com> Co-authored-by: Victor Dibia <chuvidi2003@gmail.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Fix tmp dir not exists (microsoft#401) * Fix tmp dir not exists * Update tests to make it more clear * Add check if save path is not None * feat: Qdrant vector store support (microsoft#303) * feat: QdrantRetrieveUserProxyAgent * fix: QdrantRetrieveUserProxyAgent docstring * chore: batch of 500 all CPU cores * chore: conditional import for tests * chore: config parallel, batch 100 * chore: collection creation params * chore: conditonal payload indexing fastembed import check * docs: notebook for QdrantRetrieveUserProxyAgent * docs: update docs link * docs: notebook examples update * chore: hnsw, payload index reference * docs: notebook docs_path update * Update test/agentchat/test_qdrant_retrievechat.py Co-authored-by: Li Jiang <bnujli@gmail.com> * chore: update notebook output * Fix format --------- Co-authored-by: Li Jiang <bnujli@gmail.com> * [Blocking Issue] Add tests dependencies for qdrant and fix chromadb errors (microsoft#435) * Add tests dependencies for qdrant * Update chromadb API * Update chromadb API version * Fix typehint * Add py 3.9 condition * Fix client creation error * TeachableAgent blog post (microsoft#436) * Authors * initial checkin * completed blog post * trim trailing whitespace * date * Address reviewer feedback. * Adds jupyter as a vscode extension, fix validation errors in devcontainer.json (microsoft#433) * Adds jupyter as a vscode extension, fix validation errors in vscode (see https://containers.dev/supporting#visual-studio-code) * Trim trailing whitespace * Add newline to end of file --------- Co-authored-by: Li Jiang <bnujli@gmail.com> * Update FAQ section in documentation (microsoft#390) * UPDATE - FAQ section in documentation * FIX - formatting test failure * FIX - added disclaimer * pre-commit * Update website/docs/FAQ.md Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update website/docs/FAQ.md Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update website/docs/FAQ.md Co-authored-by: Chi Wang <wang.chi@microsoft.com> * UPDATE - notebook and FAQ information for config_list_from_models --------- Co-authored-by: Ward <award40@LAMU0CLP74YXVX6.uhc.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com> Co-authored-by: Li Jiang <bnujli@gmail.com> * Add token_count_util (microsoft#421) * add token_count_util * remove token_count from retrieval util * format * update dependency * update test * spelling fix for Update math_user_proxy_agent.py (microsoft#431) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * bump version to 0.1.14 (microsoft#400) * bump version to 0.1.14 * endpoint * test * test * add ipython to retrievechat dependency * constraints * target * Update Installation.md (microsoft#456) * Update Installation.md Replace autogen->pyautogen in env setup to avoid confusion Related issue: microsoft#211 * Update Installation.md Add deactivation instructions * Update website/docs/Installation.md Co-authored-by: Chi Wang <wang.chi@microsoft.com> --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update FAQ with workaround for Issue microsoft#251 (microsoft#405) * Update FAQ with workaround for Issue microsoft#251 * Update website/docs/FAQ.md * Update website/docs/FAQ.md --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Fix typo in README.md (microsoft#481) Contributers -> Contributors * Fix/async function and tool execution (microsoft#87) * async run group chat * conversible agent allow async functions to generate reply * test for async execution --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Adding async support to get_human_input (microsoft#466) * Adding async support to get_human_input * Adjust code for Code formatting testing fail * Adjust the test_async_get_human_input.py to run async on test * Adjust the test_async_get_human_input.py for pre-commit-check error * Adjust the test_async_get_human_input.py for pre-commit-check error v2 * Adjust remove unnecessary register_reply * Adjust test to use asyncio call * Adjust go back to not use asyncio * Added example .txt file for agentchat_langchain sample notebook (microsoft#373) * Added example .txt file for agentchat_langchain sample notebook * Update radius.txt --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update README.md (microsoft#506) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Dev/v0.2 (microsoft#393) * api_base -> base_url (microsoft#383) * InvalidRequestError -> BadRequestError (microsoft#389) * remove api_key_path; close microsoft#388 * close microsoft#402 (microsoft#403) * openai client (microsoft#419) * openai client * client test * _client -> client * _client -> client * extra kwargs * Completion -> client (microsoft#426) * Completion -> client * Completion -> client * Completion -> client * Completion -> client * support aoai * fix test error * remove commented code * support aoai * annotations * import * reduce test * skip test * skip test * skip test * debug test * rename test * update workflow * update workflow * env * py version * doc improvement * docstr update * openai<1 * add tiktoken to dependency * filter_func * async test * dependency * migration guide (microsoft#477) * migration guide * change in kwargs * simplify header * update optigude description * deal with azure gpt-3.5 * add back test_eval_math_responses * timeout * Add back tests for RetrieveChat (microsoft#480) * Add back tests for RetrieveChat * Fix format * Update dependencies order * Fix path * Fix path * Fix path * Fix tests * Add not run openai on MacOS or Win * Update skip openai tests * Remove unnecessary dependencies, improve format * Add py3.8 for testing qdrant * Fix multiline error of windows * Add openai tests * Add dependency mathchat, remove unused envs * retrieve chat is tested * bump version to 0.2.0b1 --------- Co-authored-by: Li Jiang <bnujli@gmail.com> * Added a simple Testbed tool for repeatedly running templated Autogen scenarios with tightly-controlled initial conditions. (microsoft#455) * Initial commit of the autogen testbed environment. * Fixed some typos in the Testbed README.md * Added some stricter termination logic to the two_agent scenario, and swiched the logo task from finding Autogen's logo, to finding Microsoft's (it's easier) * Added documentation to testbed code in preparation for PR * Added a variation of HumanEval to the Testbed. It is also a reasonable example of how to integrate other benchmarks. * Removed ChatCompletion.start_logging and related features. Added an explicit TERMINATE output to HumanEval to save 1 turn in each conversation. * Added metrics utils script for HumanEval * Updated the requirements in the README. * Added documentation for HumanEval csv schemas * Standardized on how the OAI_CONFIG_LIST is handled. * Removed dot-slash from 'includes' path for cross-platform compatibility * Missed a file. * Updated readme to include known-working versions. * Fix typo import autogen (microsoft#549) * Add support to unstructrued (microsoft#501) * Add support to unstructrued * Fix tests * Add test and documents * Fix tests * Fix tests * Test unstructured on linux and mac * Update TRANSPARENCY_FAQS.md (microsoft#492) fixed grammatical error FAQ--->FAQs Co-authored-by: gagb <gagb@users.noreply.github.com> * Update README.md (microsoft#507) Fixed small typos Co-authored-by: Chi Wang <wang.chi@microsoft.com> * fix wrong 'Langchain Provided Tools as Functions' doc ref (microsoft#495) Co-authored-by: Chi Wang <wang.chi@microsoft.com> * copy dicts before modifying (microsoft#551) * copy dicts before modifying * update notebooks * update notebooks * close microsoft#567 * Large Multimodal Models in AgentChat (microsoft#554) * LMM Code added * LLaVA notebook update * Test cases and Notebook modified for OpenAI v1 * Move LMM into contrib To resolve test issues and deploy issues In the future, we can install pillow by default, and then move back LMM agents into agentchat * LMM test setup update * try...except... clause for LMM tests * disable patch for llava agent test To resolve dependencies issue for build * Add LMM Blog * Change docstring for LMM agents * Docstring update patch * llava: insert reply at position 1 now So, it can still handle human_input_mode and max_consecutive_reply * Resolve comments Fixing: typos, blogs, yml, and add OpenAIWrapper * Signature typo fix for LMM agent: system_message * Update LMM "content" from latest OpenAI release Reference https://platform.openai.com/docs/guides/vision * update LMM test according to latest OpenAI release * Fully support GPT-4V now 1. Add a notebook for GPT-4V. LLava notebook also updated. 2. img_utils updated 3. GPT-4V formatter now return base64 image with mime type 4. Infer mime type directly from b64 image content (while loading without suffix) 5. Test cases modified according to all the related changes. * GPT-4V link updated in blog --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * update version of openai dependency (microsoft#588) * Notebook/hierarchy flow (microsoft#482) * Notebook showing how to use select speaker to control conversation flow. * pytest associated with notebook. * Added llm_config to assistant and user proxy agent, and clarified why we set use_cache to false, as requested in the review. * Added a @pytest.mark.skipif decorator like other tests to run it only in one py version, 3.10 * Fixed config warning. * Removd llm_config to UserProxyAgent * Fixed minor typos. * Reran outputs * Remopved llm_config from user_proxy_agent * Colab Badge link updated. * pre-commit formatting changes. * Fixed base_url --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * seed -> cache_seed (microsoft#600) * Added link to the new notebook (microsoft#594) * update return type of WolframAlphaAPIWrapper.run() (microsoft#523) * update return type of WolframAlphaAPIWrapper.run * replace tuple by typing.Tuple --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> Co-authored-by: Yiran Wu <32823396+kevin666aa@users.noreply.github.com> * news update (microsoft#609) * news update * separate lines * Add EcoAssistant to the research page (microsoft#612) * Update Research.md * Update Research.md * Update Research.md * Add CompressibleAgent (microsoft#443) * api_base -> base_url (microsoft#383) * InvalidRequestError -> BadRequestError (microsoft#389) * remove api_key_path; close microsoft#388 * close microsoft#402 (microsoft#403) * openai client (microsoft#419) * openai client * client test * _client -> client * _client -> client * extra kwargs * Completion -> client (microsoft#426) * Completion -> client * Completion -> client * Completion -> client * Completion -> client * support aoai * fix test error * remove commented code * support aoai * annotations * import * reduce test * skip test * skip test * skip test * debug test * rename test * update workflow * update workflow * env * py version * doc improvement * docstr update * openai<1 * add compressibleagent * revise doc, add tests, add example * fix link * fix link * fix link * remove test * update doc * update doc * add tiktoken to dependency * filter_func * async test * dependency * revision * migration guide (microsoft#477) * migration guide * change in kwargs * simplify header * update optigude description * update for dev * revision * revision * allow not compressing last n msgs * update * correct merge * update test workflow * check test * update for test * update * update notebook * update * fix bug * update * update * update * check to "pull_request_target" in contrib-openai --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * add AutoGen paper info at the beginning of readme (microsoft#621) * add paper info on top of readme * update info * add paper info * revise date * Update oai_completion.ipynb (microsoft#623) Missing import * Added warnings for some GroupChat misconfigurations and selection errors (microsoft#603) * Added warnings for some GroupChat misconfigurations and selection errors * Fixed formatting * Introducing Experimental GPT Assistant Agent in AutoGen (microsoft#616) * add gpt assistant agent * complete code * Inherit class ConversableAgent * format code * add code comments * add test case * format code * fix test * format code * Improve GPTAssistant * Use OpenAIWrapper to create client * Implement clear_history() * Reply message formatting improvements * Handle the case when content contains image files * README update * Fix doc string of methods * add multiple conversations support * Add GPT Assistant Agent into README * fix test --------- Co-authored-by: gagb <gagb@users.noreply.github.com> Co-authored-by: Beibin Li <beibin79@gmail.com> * added twitter(X) banner + link to readme (microsoft#615) * added twitter(X) banner + link to readme * Update README.md Fix typo in the label --------- Co-authored-by: gagb <gagb@users.noreply.github.com> * Enable streaming support for openai v1 (microsoft#597) * Enable streaming support for openai v1 * Added tests for openai client streaming * Fix test_completion_stream * improve readme (microsoft#630) * improve readme * Update README.md Co-authored-by: Chi Wang <wang.chi@microsoft.com> --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Handled possible unclear IndexError in ConversableAgent.last_message method (microsoft#622) * Handled possible IndexError in ConversableAgent.last_message method with more clear error message and added test in test_conversable_agent.py. * Fix code formatting issues. --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Fix test error of compressible agent (microsoft#631) * fix bug in test * update workflow * update * deepcopy to copy * Fix docstring of get_or_create (microsoft#583) * Fix docstring of get_or_create * Improve docstring * Refactor GPTAssistantAgent (microsoft#632) * Refactor GPTAssistantAgent constructor to handle instructions and overwrite_instructions flag - Ensure that `system_message` is always consistent with `instructions` - Ensure provided instructions are always used - Add option to permanently modify the instructions of the assistant * Improve default behavior * Add a test; add method to delete assistant * Add a new test for overwriting instructions * Add test case for when no instructions are given for existing assistant * Add pytest markers to test_gpt_assistant.py * add test in workflow * update * fix test_client_stream * comment out test_hierarchy_ --------- Co-authored-by: Chi Wang <wang.chi@microsoft.com> Co-authored-by: kevin666aa <yrwu000627@gmail.com> * uncomment test (microsoft#640) --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Juanma Cuevas <jumacuca@gmail.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com> Co-authored-by: Li Jiang <bnujli@gmail.com> Co-authored-by: Ali Eren SALKIM <129160641+AlyrenN@users.noreply.github.com> Co-authored-by: Aaron <aaronlaptop12@hotmail.com> Co-authored-by: Ward <award40@LAMU0CLP74YXVX6.uhc.com> Co-authored-by: Priyanshu Yashwant Deshmukh <69320370+priyansh4320@users.noreply.github.com> Co-authored-by: Xiaoyun Zhang <bigmiao.zhang@gmail.com> Co-authored-by: Hiftie <127197446+hiftielabs@users.noreply.github.com> Co-authored-by: Yiran Wu <32823396+kevin666aa@users.noreply.github.com> Co-authored-by: Shaurya Rohatgi <shauryr@gmail.com> Co-authored-by: Al-Ekram Elahee Hridoy <aliqramalaheehridoy@gmail.com> Co-authored-by: Al-Iqram Elahee <hridoy@Al-Iqrams-MacBook-Pro.local> Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu> Co-authored-by: Mohamed Attia <mu.attiyah@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Ujjwal gupta <guptarickey3@gmail.com> Co-authored-by: lars.gersmann <lars.gersmann@gmail.com> Co-authored-by: Hyung-Taik Choi <htc.refactor@gmail.com> Co-authored-by: Tristan Murphy <72839119+HyperCodec@users.noreply.github.com> Co-authored-by: Sagar Desai <60027013+SDcodehub@users.noreply.github.com> Co-authored-by: Sagar Desai <60027013+sagardesai-ml-mlops@users.noreply.github.com> Co-authored-by: mrauter1 <marcelorauter@gmail.com> Co-authored-by: Manish Kumar <51908018+manish7017@users.noreply.github.com> Co-authored-by: Olaoluwa Ademola Salami <oyomafia@gmail.com> Co-authored-by: Olaoluwa Ademola Salami <olaoluwaasalami@gmail.com> Co-authored-by: Vidhula <58629266+vidhula17@users.noreply.github.com> Co-authored-by: vidhula17 <catchvidhula@gmail.com> Co-authored-by: Allen Shi <33379392+AllenJShi@users.noreply.github.com> Co-authored-by: afourney <adam.fourney@gmail.com> Co-authored-by: afourney <adamfo@microsoft.com> Co-authored-by: Li Jiang <lijiang1@microsoft.com> Co-authored-by: Ikko Eltociear Ashimine <eltociear@gmail.com> Co-authored-by: wayliums <wayliums@users.noreply.github.com> Co-authored-by: Manuel Saelices <msaelices@gmail.com> Co-authored-by: gagb <gagb@users.noreply.github.com> Co-authored-by: Deepanshu <91846266+creator0131@users.noreply.github.com> Co-authored-by: Gaëtan H <gaetanhus@gmail.com> Co-authored-by: Javid Jamae <javidjamae@gmail.com> Co-authored-by: Sheetali Maity <74114936+smty2018@users.noreply.github.com> Co-authored-by: James Tsang <wtzeng1@gmail.com> Co-authored-by: Hitesh Bansal <83907989+05hiteshbansal@users.noreply.github.com> Co-authored-by: Shruti Patel <shruti222patel@users.noreply.github.com> Co-authored-by: Gourav <herculeswarrior.in@gmail.com> Co-authored-by: Elliot Wood <gigaflare_elliot@hotmail.com> Co-authored-by: Maxim Saplin <smaxmail@gmail.com> Co-authored-by: Ayush Kumar Pandit <31253617+Ayushpanditmoto@users.noreply.github.com> Co-authored-by: Surav Shrestha <148448735+suravkshrestha@users.noreply.github.com> Co-authored-by: Victor Dibia <chuvidi2003@gmail.com> Co-authored-by: Haseeb Ansari <47222685+haseeb-xd@users.noreply.github.com> Co-authored-by: Ricky Loynd <riloynd@microsoft.com> Co-authored-by: Sean Connelly <47223469+2good4hisowngood@users.noreply.github.com> Co-authored-by: Ishita Pathak <75848598+IshitaPathak@users.noreply.github.com> Co-authored-by: Ansh Babbar <31804810+rabbabansh@users.noreply.github.com> Co-authored-by: Beibin Li <BeibinLi@users.noreply.github.com> Co-authored-by: Ragy Abraham <52903382+ragyabraham@users.noreply.github.com> Co-authored-by: Anush <anushshetty90@gmail.com> Co-authored-by: Craig Presti <146438+craigomatic@users.noreply.github.com> Co-authored-by: rajpal <codingdrone@gmail.com> Co-authored-by: Marc Green <marcgreen@users.noreply.github.com> Co-authored-by: Aayush Chhabra <aayushgen@gmail.com> Co-authored-by: bonadio <cesar.bonadio@gmail.com> Co-authored-by: Jason Holtkamp <holtkam2@gmail.com> Co-authored-by: Aditya <114663382+AaadityaG@users.noreply.github.com> Co-authored-by: hung_ng__ <51025722+hung-ngm@users.noreply.github.com> Co-authored-by: gfggithubleet <144522681+gfggithubleet@users.noreply.github.com> Co-authored-by: Vatsalya Vyas <vatsalyavyas@gmail.com> Co-authored-by: AkariLan <850439027@qq.com> Co-authored-by: Joshua Kim <joshkyh@users.noreply.github.com> Co-authored-by: 1073710317 <1073710317@163.com> Co-authored-by: Jieyu Zhang <jieyuz2@cs.washington.edu> Co-authored-by: Andreas Volkmann <avolkmann@icloud.com> Co-authored-by: Ian <ArGregoryIan@gmail.com> Co-authored-by: Beibin Li <beibin79@gmail.com> Co-authored-by: Malik Muhammad Moaz <40146994+malikmmoaz@users.noreply.github.com> Co-authored-by: Alvaro Mateos <Alvaromah@users.noreply.github.com> Co-authored-by: wonderful <3269753363@qq.com> Co-authored-by: kevin666aa <yrwu000627@gmail.com>
whiskyboy
pushed a commit
to whiskyboy/autogen
that referenced
this pull request
Apr 17, 2024
jackgerrits
added a commit
that referenced
this pull request
Oct 2, 2024
* add checks for notebooks * format * Fix mypy * format --------- Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
SHAM560
added a commit
to SHAM560/autogen
that referenced
this pull request
Dec 20, 2025
Здесь сделай чтоб присадку делал согласно локальных координат компонентов, так как сейчас на повёрнутых под определённый градус угла компонентах не делает присадок потому что делает присадку согласно мировых координат что не допустимо. Пиши полный код целиком.
require 'sketchup.rb'
require 'extensions.rb'
module ABFStyleDrill
# Настройки по умолчанию
DEFAULTS = {
:cam_diameter => 8.0, # Диаметр отверстия в пласть (Cam)
:screw_diameter => 5.0, # Диаметр отверстия в торец (Screw)
:offset => 50.0, # Отступ от края детали для присадки
:hole_count => 2, # Количество присадочных отверстий
:marker_length => 15.0, # Длина проекции (маркера) для торцевого отверстия
# --- НОВЫЕ НАСТРОЙКИ ДЛЯ ПЕТЕЛЬ ---
:hinge_diameter => 35.0, # Диаметр отверстия под чашку петли (35мм)
:hinge_offset => 100.0, # Отступ от края детали для первой петли (100мм) - Смещение по длине
:hinge_count => 2, # Количество петель
:hinge_side_offset => 21.5, # Смещение от бокового края компонента (21.5мм)
:hinge_screw_diameter => 5.0, # Диаметр отверстий под саморезы (5мм)
:hinge_screw_spacing => 45.0, # Расстояние между центрами отверстий под саморезы (45мм)
:hinge_screw_vertical_offset => 9.5, # НОВОЕ: Смещение отверстий под саморезы от центра чашки (9.5мм)
# --- НОВЫЕ НАСТРОЙКИ ДЛЯ ПЛАНКИ ---
:strip_diameter => 5.0, # Диаметр отверстия под планку (5мм)
:strip_spacing => 32.0, # Межосевое расстояние (32мм)
:strip_side_offset => 37.0, # Смещение от края боковины (37мм)
:strip_offset => 100.0 # НОВОЕ: Отступ от короткого края (100мм)
}
# Константа для зазора между деталями при раскладке
GAP = 500.0.mm
# Переменная для отслеживания состояния аннотаций
@annotations_visible = false
# --- МЕТОД: Очистка ранее созданных аннотаций (размеров) ---
def self.cleanup_annotations(entities)
entities_to_remove = []
entities.each do |e|
if e.is_a?(Sketchup::DimensionLinear) && e.get_attribute('ABFDrill', 'Type') == 'Dimension'
entities_to_remove << e
end
end
entities.erase_entities(entities_to_remove) if entities_to_remove.any?
end
# --- МЕТОД: Очистка только стандартных присадочных отверстий и маркеров ---
def self.cleanup_standard_drill_geometry(entity)
defn = entity.respond_to?(:definition) ? entity.definition : entity.entities.parent
entities_to_remove = []
defn.entities.each do |e|
# Удаляем всё, что помечено как DrillHole
type = e.get_attribute('ABFDrill', 'Type')
if type == 'DrillHole'
entities_to_remove << e
end
end
defn.entities.erase_entities(entities_to_remove) if entities_to_remove.any?
end
# --- МЕТОД: Очистка только отверстий под петли ---
def self.cleanup_hinge_drill_geometry(entity)
defn = entity.respond_to?(:definition) ? entity.definition : entity.entities.parent
entities_to_remove = []
defn.entities.each do |e|
# Удаляем всё, что помечено как HingeHole
type = e.get_attribute('ABFDrill', 'Type')
if type == 'HingeHole'
entities_to_remove << e
end
end
defn.entities.erase_entities(entities_to_remove) if entities_to_remove.any?
end
# --- НОВЫЙ МЕТОД: Очистка только отверстий под планку ---
def self.cleanup_strip_drill_geometry(entity)
defn = entity.respond_to?(:definition) ? entity.definition : entity.entities.parent
entities_to_remove = []
defn.entities.each do |e|
# Удаляем всё, что помечено как StripHole (включая новую точку)
type = e.get_attribute('ABFDrill', 'Type')
if type == 'StripHole'
entities_to_remove << e
end
end
defn.entities.erase_entities(entities_to_remove) if entities_to_remove.any?
end
# --- МЕТОД: Отображение диалогового окна (Обновлено для передачи параметров петель в планку) ---
def self.show_dialog
dialog = UI::HtmlDialog.new(
{
:dialog_title => "ABF Style Drill & Hinges",
:preferences_key => "com.abfstyle.drill",
:scrollable => true,
:resizable => true,
:width => 350,
:height => 850, # Увеличена высота для новых настроек
:style => UI::HtmlDialog::STYLE_DIALOG
}
)
html_content = <<-HTML
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; background-color: microsoft#333; color: white; }
h3 { margin-top: 20px; color: #ff9800; border-bottom: 1px solid microsoft#555; padding-bottom: 10px; }
.control { margin-bottom: 15px; }
label { display: flex; justify-content: space-between; align-items: center; font-size: 14px; }
input { width: 80px; padding: 5px; border-radius: 4px; border: none; text-align: center; }
button {
width: 100%; padding: 12px; margin-top: 10px;
background-color: #ff9800; color: white; border: none;
border-radius: 4px; cursor: pointer; font-weight: bold; font-size: 16px;
transition: background 0.3s;
}
button:hover { background-color: #e68900; }
.hint { font-size: 11px; color: #aaa; margin-top: 5px; }
.secondary-button { background-color: microsoft#555; }
.secondary-button:hover { background-color: microsoft#777; }
.annotation-button { background-color: #00bcd4; }
.annotation-button:hover { background-color: #0097a7; }
.hinge-button { background-color: #4CAF50; }
.hinge-button:hover { background-color: #45a049; }
/* НОВЫЙ СТИЛЬ ДЛЯ КНОПКИ ПЛАНКИ */
.strip-button { background-color: #9c27b0; }
.strip-button:hover { background-color: #7b1fa2; }
</style>
</head>
<body>
<!-- --- НОВАЯ СЕКЦИЯ ДЛЯ ПЛАНКИ (ПЕРЕМЕЩЕНА ВЫШЕ) --- -->
<h3>Присадка планки</h3>
<div class="control">
<label>Диаметр отверстий (мм) <input type="number" id="strip_dia" value="#{DEFAULTS[:strip_diameter]}" step="0.5"></label>
</div>
<div class="control">
<label>Межосевое (мм) <input type="number" id="strip_spacing" value="#{DEFAULTS[:strip_spacing]}" step="1.0"></label>
</div>
<div class="control">
<label>Смещение от края (мм) <input type="number" id="strip_side_off" value="#{DEFAULTS[:strip_side_offset]}" step="1.0"></label>
</div>
<!-- НОВЫЙ ИНПУТ ДЛЯ СМЕЩЕНИЯ ПЛАНКИ -->
<div class="control">
<label>Смещение по длине (мм) <input type="number" id="strip_off" value="#{DEFAULTS[:strip_offset]}" step="1.0"></label>
<div class="hint">Отступ первой планки от короткого края.</div>
</div>
<button class="strip-button" onclick="run_strip_drill()">ПРИСАДКА ПЛАНКИ</button>
<!-- --- КОНЕЦ НОВОЙ СЕКЦИИ --- -->
<h3>Настройки присадки (Minifix)</h3>
<div class="control">
<label>Количество отверстий <input type="number" id="hole_count" value="#{DEFAULTS[:hole_count]}" step="1" min="1" oninput="update_model_realtime()"></label>
<div class="hint">Общее количество на стык.</div>
</div>
<div class="control">
<label>Диаметр (Пласть/Cam) <input type="number" id="cam_dia" value="#{DEFAULTS[:cam_diameter]}" step="0.5" oninput="update_model_realtime()"></label>
</div>
<div class="control">
<label>Диаметр (Торец/Screw) <input type="number" id="screw_dia" value="#{DEFAULTS[:screw_diameter]}" step="0.5" oninput="update_model_realtime()"></label>
</div>
<div class="control">
<label>Длина маркера (мм) <input type="number" id="marker_len" value="#{DEFAULTS[:marker_length]}" step="1.0" min="0" oninput="update_model_realtime()"></label>
<div class="hint">Длина проекции торцевого отверстия.</div>
</div>
<div class="control">
<label>Отступ от края (мм) <input type="number" id="off" value="#{DEFAULTS[:offset]}" step="1" oninput="update_model_realtime()"></label>
</div>
<button onclick="run()">ПРИСАДИТЬ (Auto)</button>
<!-- --- НОВАЯ СЕКЦИЯ ДЛЯ ПЕТЕЛЬ --- -->
<h3>Настройки петель</h3>
<div class="control">
<label>Количество кругов <input type="number" id="hinge_count" value="#{DEFAULTS[:hinge_count]}" step="1" min="1"></label>
</div>
<div class="control">
<label>Диаметр чашки (мм) <input type="number" id="hinge_dia" value="#{DEFAULTS[:hinge_diameter]}" step="1.0"></label>
</div>
<!-- НОВЫЕ ИНПУТЫ ДЛЯ ОТВЕРСТИЙ ПОД САМОРЕЗЫ -->
<div class="control">
<label>Диаметр саморезов (мм) <input type="number" id="hinge_screw_dia" value="#{DEFAULTS[:hinge_screw_diameter]}" step="0.5"></label>
</div>
<div class="control">
<label>Расстояние между (мм) <input type="number" id="hinge_screw_spacing" value="#{DEFAULTS[:hinge_screw_spacing]}" step="1.0"></label>
<div class="hint">Расстояние между центрами отверстий под саморезы (45мм).</div>
</div>
<!-- НОВЫЙ ИНПУТ ДЛЯ СМЕЩЕНИЯ САМОРЕЗОВ ОТНОСИТЕЛЬНО ЧАШКИ -->
<div class="control">
<label>Смещение саморезов (мм) <input type="number" id="hinge_screw_vert_off" value="#{DEFAULTS[:hinge_screw_vertical_offset]}" step="0.5"></label>
<div class="hint">Смещение отверстий от центра чашки (вдоль 21.5мм оси).</div>
</div>
<!-- КОНЕЦ НОВЫХ ИНПУТОВ -->
<div class="control">
<label>Смещение по длине (мм) <input type="number" id="hinge_off" value="#{DEFAULTS[:hinge_offset]}" step="1.0"></label>
<div class="hint">Отступ первой петли от короткого края.</div>
</div>
<div class="control">
<label>Смещение от края компонента (мм) <input type="number" id="hinge_side_off" value="#{DEFAULTS[:hinge_side_offset]}" step="0.5"></label>
<div class="hint">Смещение центра чашки от бокового края (21.5мм).</div>
</div>
<button class="hinge-button" onclick="run_hinges()">ПЕТЛИ</button>
<!-- --- КОНЕЦ НОВОЙ СЕКЦИИ --- -->
<button class="secondary-button" onclick="line_up()">РАЗЛОЖИТЬ</button>
<button class="annotation-button" onclick="show_annotations()">АННОТАЦИИ</button>
<script>
function debounce(func, timeout = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}
function get_input_values() {
return {
cam_dia: parseFloat(document.getElementById('cam_dia').value),
screw_dia: parseFloat(document.getElementById('screw_dia').value),
off: parseFloat(document.getElementById('off').value),
hole_count: parseInt(document.getElementById('hole_count').value),
marker_len: parseFloat(document.getElementById('marker_len').value)
};
}
// --- НОВАЯ ФУНКЦИЯ ДЛЯ ПОЛУЧЕНИЯ ЗНАЧЕНИЙ ПЕТЕЛЬ (ОБНОВЛЕНО) ---
function get_hinge_values() {
return {
hinge_count: parseInt(document.getElementById('hinge_count').value),
hinge_dia: parseFloat(document.getElementById('hinge_dia').value),
hinge_off: parseFloat(document.getElementById('hinge_off').value),
hinge_side_off: parseFloat(document.getElementById('hinge_side_off').value),
// НОВЫЕ ЗНАЧЕНИЯ
hinge_screw_dia: parseFloat(document.getElementById('hinge_screw_dia').value),
hinge_screw_spacing: parseFloat(document.getElementById('hinge_screw_spacing').value),
hinge_screw_vertical_offset: parseFloat(document.getElementById('hinge_screw_vert_off').value)
};
}
// --- НОВАЯ ФУНКЦИЯ ДЛЯ ПОЛУЧЕНИЯ ЗНАЧЕНИЙ ПЛАНКИ (ОБНОВЛЕНО) ---
function get_strip_values() {
return {
strip_dia: parseFloat(document.getElementById('strip_dia').value),
strip_spacing: parseFloat(document.getElementById('strip_spacing').value),
strip_side_off: parseFloat(document.getElementById('strip_side_off').value),
strip_offset: parseFloat(document.getElementById('strip_off').value), // ДОБАВЛЕНО
// ДОБАВЛЕНЫ ЗНАЧЕНИЯ ПЕТЕЛЬ ДЛЯ ПОЗИЦИОНИРОВАНИЯ ПЛАНКИ
hinge_count: parseInt(document.getElementById('hinge_count').value)
};
}
function run() {
var values = get_input_values();
sketchup.do_drill(values.cam_dia, values.screw_dia, values.off, values.hole_count, values.marker_len);
}
// --- НОВАЯ ФУНКЦИЯ ДЛЯ ЗАПУСКА ПЕТЕЛЬ (ОБНОВЛЕНО) ---
function run_hinges() {
var values = get_hinge_values();
// Передаем новые значения
sketchup.do_hinges(
values.hinge_count,
values.hinge_dia,
values.hinge_off,
values.hinge_side_off,
values.hinge_screw_dia,
values.hinge_screw_spacing,
values.hinge_screw_vertical_offset
);
}
// --- НОВАЯ ФУНКЦИЯ ДЛЯ ЗАПУСКА ПЛАНКИ (ОБНОВЛЕНО) ---
function run_strip_drill() {
var values = get_strip_values();
sketchup.do_strip_drill(
values.strip_dia,
values.strip_spacing,
values.strip_side_off,
// ПЕРЕДАЕМ ПАРАМЕТРЫ ДЛЯ ПОЗИЦИОНИРОВАНИЯ
values.hinge_count,
values.strip_offset // ИСПОЛЬЗУЕМ НОВОЕ СМЕЩЕНИЕ
);
}
const debounced_update_callback = debounce(function() {
var values = get_input_values();
sketchup.update_drill_realtime(values.cam_dia, values.screw_dia, values.off, values.hole_count, values.marker_len);
}, 300);
function update_model_realtime() { debounced_update_callback(); }
function line_up() { sketchup.line_up_components(); }
function show_annotations() { sketchup.show_drill_annotations(); }
window.onload = function() { update_model_realtime(); };
</script>
</body>
</html>
HTML
dialog.set_html(html_content)
dialog.center
dialog.add_action_callback("do_drill") do |ctx, cam_dia, screw_dia, off, hole_count, marker_len|
self.process_model(cam_dia, screw_dia, off, hole_count, marker_len)
end
dialog.add_action_callback("update_drill_realtime") do |ctx, cam_dia, screw_dia, off, hole_count, marker_len|
self.process_model(cam_dia, screw_dia, off, hole_count, marker_len)
end
# --- CALLBACK ДЛЯ ПЕТЕЛЬ ---
dialog.add_action_callback("do_hinges") do |ctx, count, diameter, length_offset, side_offset, screw_diameter, screw_spacing, screw_vert_offset|
self.process_hinge_holes(count, diameter, length_offset, side_offset, screw_diameter, screw_spacing, screw_vert_offset)
end
# --- НОВЫЙ CALLBACK ДЛЯ ПЛАНКИ (ОБНОВЛЕНО) ---
# Изменено: hinge_offset заменен на length_offset (который теперь strip_offset)
dialog.add_action_callback("do_strip_drill") do |ctx, diameter, spacing, side_offset, count, length_offset|
self.process_strip_holes(diameter, spacing, side_offset, count, length_offset)
end
dialog.add_action_callback("line_up_components") { |ctx| self.line_up_components }
dialog.add_action_callback("show_drill_annotations") { |ctx| self.show_drill_annotations }
dialog.show
end
# --- ГЛАВНЫЙ ПРОЦЕСС ПРИСАДКИ (Minifix) ---
def self.process_model(cam_diameter_mm, screw_diameter_mm, offset_mm, hole_count, marker_length_mm)
model = Sketchup.active_model
selection = model.selection
items = selection.grep(Sketchup::ComponentInstance) + selection.grep(Sketchup::Group)
# Если выделено меньше 2-х, очищаем присадки только на выделенных и выходим
if items.length < 2
model.start_operation("ABF Drill Cleanup", true)
items.each { |ent| self.cleanup_standard_drill_geometry(ent) }
model.commit_operation
return
end
model.start_operation("ABF Style Drill Update", true)
# Очищаем только стандартные присадки на выделенных компонентах
items.each { |ent| self.cleanup_standard_drill_geometry(ent) }
processed_pairs = 0
(0...items.length).each do |i|
((i + 1)...items.length).each do |j|
ent1 = items[i]
ent2 = items[j]
# Проверяем пересечение
if ent1.bounds.intersect(ent2.bounds).valid?
if self.apply_drill_to_pair(ent1, ent2, cam_diameter_mm.mm, screw_diameter_mm.mm, offset_mm.mm, hole_count, marker_length_mm.mm)
processed_pairs += 1
end
end
end
end
model.commit_operation
end
# ... (get_diameter остается без изменений)
def self.get_diameter(entity, global_drill_axis, cam_dia, screw_dia)
trans_inv = entity.transformation.inverse
local_drill_axis = global_drill_axis.transform(trans_inv)
bb_local = entity.bounds
w, h, d = bb_local.width, bb_local.height, bb_local.depth
dims = { w => Geom::Vector3d.new(1, 0, 0), h => Geom::Vector3d.new(0, 1, 0), d => Geom::Vector3d.new(0, 0, 1) }
min_dim = dims.keys.min
local_thickness_axis = dims[min_dim]
dot_product = local_drill_axis.dot(local_thickness_axis).abs
return (dot_product > 0.999) ? cam_dia : screw_dia
end
# --- ОСНОВНАЯ ЛОГИКА ПРИСАДКИ И ГЕОМЕТРИИ (Minifix) ---
def self.apply_drill_to_pair(ent1, ent2, cam_diameter, screw_diameter, offset, hole_count, marker_length)
bb1 = ent1.bounds
bb2 = ent2.bounds
intersect = bb1.intersect(bb2)
return false if intersect.empty?
w, h, d = intersect.width, intersect.height, intersect.depth
dims = [w, h, d]
min_dim = dims.min
return false if dims.max < 10.mm
drill_axis = Geom::Vector3d.new(0,0,1)
long_axis_vec = Geom::Vector3d.new(1,0,0)
center = intersect.center
if min_dim == w
drill_axis = Geom::Vector3d.new(1, 0, 0)
long_axis_vec = (h > d) ? Geom::Vector3d.new(0, 1, 0) : Geom::Vector3d.new(0, 0, 1)
len = [h, d].max
elsif min_dim == h
drill_axis = Geom::Vector3d.new(0, 1, 0)
long_axis_vec = (w > d) ? Geom::Vector3d.new(1, 0, 0) : Geom::Vector3d.new(0, 0, 1)
len = [w, d].max
else
drill_axis = Geom::Vector3d.new(0, 0, 1)
long_axis_vec = (w > h) ? Geom::Vector3d.new(1, 0, 0) : Geom::Vector3d.new(0, 1, 0)
len = [w, h].max
end
drill_points = []
hole_count = [1, hole_count.to_i].max
max_drill_length = len - (offset * 2)
if hole_count == 1 || max_drill_length < 0.mm
drill_points << center
else
spacing = max_drill_length / (hole_count - 1).to_f
start_dist_from_center = (len / 2.0) - offset
start_point = center - long_axis_vec.clone.tap { |v| v.length = start_dist_from_center }
(0...hole_count).each do |i|
current_offset = long_axis_vec.clone.tap { |v| v.length = i * spacing }
drill_points << start_point + current_offset
end
end
[ent1, ent2].each do |ent|
defn = ent.respond_to?(:definition) ? ent.definition : ent.entities.parent
trans_inv = ent.transformation.inverse
current_diameter = self.get_diameter(ent, drill_axis, cam_diameter, screw_diameter)
drill_points.each do |global_pt|
local_pt = global_pt.transform(trans_inv)
local_axis = drill_axis.transform(trans_inv)
# Вынос на внешнюю сторону для отверстий в пласть
if current_diameter == cam_diameter
bounds = defn.bounds
bounds_center = bounds.center
axis_idx = local_axis.to_a.map(&:abs).each_with_index.max[1]
dir_val = bounds_center[axis_idx] - local_pt[axis_idx]
dir_val = 1.0 if dir_val.abs < 0.0001
target_coordinate = (dir_val > 0) ? bounds.max[axis_idx] : bounds.min[axis_idx]
local_pt[axis_idx] = target_coordinate
end
# 1. Создаем само отверстие (круг)
circle = defn.entities.add_circle(local_pt, local_axis, current_diameter / 2.0)
cpoint = defn.entities.add_cpoint(local_pt)
circle.each { |e| e.set_attribute('ABFDrill', 'Type', 'DrillHole') }
cpoint.set_attribute('ABFDrill', 'Type', 'DrillHole')
# 2. Логика для рисования прямоугольника-проекции (только линии)
if current_diameter == screw_diameter && marker_length > 0.0.mm
bounds = defn.bounds
# Определяем ось толщины (самая короткая сторона)
b_dims = [bounds.width, bounds.height, bounds.depth]
min_b_dim = b_dims.min
thick_axis_idx = b_dims.index(min_b_dim)
# Вектор нормали к грани (ось толщины)
face_normal = Geom::Vector3d.new(0,0,0)
face_normal[thick_axis_idx] = 1
# Вектор "ширины" прямоугольника
width_vec = local_axis.cross(face_normal)
if width_vec.length > 0.001
width_vec.length = current_diameter / 2.0
# Вектор "длины" маркера, используем значение из инпута
marker_len_vec = local_axis.clone
# Направление: Внутрь детали
vec_to_center = bounds.center - local_pt
if vec_to_center.dot(marker_len_vec) < 0
marker_len_vec.reverse!
end
marker_len_vec.length = marker_length
# Рисуем прямоугольники на обеих плоскостях
faces_coords = [bounds.min[thick_axis_idx], bounds.max[thick_axis_idx]]
faces_coords.each do |z_coord|
pt_on_face = local_pt.clone
pt_on_face[thick_axis_idx] = z_coord
# 4 точки прямоугольника
p1 = pt_on_face + width_vec
p2 = pt_on_face - width_vec
p3 = p2 + marker_len_vec
p4 = p1 + marker_len_vec
# Создаем группу для маркера
m_group = defn.entities.add_group
# Создаем Face, чтобы потом его удалить, но сохранить Edges
m_face = m_group.entities.add_face(p1, p2, p3, p4)
if m_face
# УДАЛЯЕМ ГРАНЬ, ОСТАВЛЯЯ ТОЛЬКО ЛИНИИ (Edges)
m_face.erase!
# Метим группу как DrillHole для очистки
m_group.set_attribute('ABFDrill', 'Type', 'DrillHole')
else
# Если грань не создалась, удаляем пустую группу
m_group.erase!
end
end
end
end
# --- КОНЕЦ ЛОГИКИ ПРЯМОУГОЛЬНИКА ---
end
end
return true
end
# --- ИСПРАВЛЕННЫЙ МЕТОД: Рисование компенсированного круга ---
# Этот метод создает круг, который останется кругом даже после не-униформного масштабирования
def self.draw_drill_hole_geometry(entity, center_pt, radius, normal_axis, type_tag)
defn_entities = entity.respond_to?(:definition) ? entity.definition.entities : entity.entities
trans = entity.transformation
# 1. Получаем обратную трансформацию для компенсации масштабирования
inv_trans = trans.inverse
# 2. Получаем мировые оси, преобразованные в локальные координаты определения
world_axes = [
Geom::Vector3d.new(1, 0, 0),
Geom::Vector3d.new(0, 1, 0),
Geom::Vector3d.new(0, 0, 1)
]
# 3. Преобразуем нормаль в мировые координаты
world_normal = normal_axis.transform(trans)
# 4. Находим две оси, ортогональные нормали (в мировых координатах)
world_axes_in_plane = world_axes.reject { |axis| axis.parallel?(world_normal) }
if world_axes_in_plane.length < 2
# Если не можем найти оси, используем альтернативный метод
world_axes_in_plane = [
world_normal.axes[0],
world_normal.axes[1]
]
end
axis1 = world_axes_in_plane[0]
axis2 = world_axes_in_plane[1]
# 5. Преобразуем оси обратно в локальные координаты определения
local_axis1 = axis1.transform(inv_trans)
local_axis2 = axis2.transform(inv_trans)
# 6. Нормализуем оси
local_axis1.normalize!
local_axis2.normalize!
# 7. Убеждаемся, что оси ортогональны
if local_axis1.dot(local_axis2) > 0.001
# Делаем axis2 ортогональным axis1
local_axis2 = local_axis2 - local_axis1 * local_axis1.dot(local_axis2)
local_axis2.normalize!
end
# 8. Создаем круг с использованием add_circle (который Sketchup корректно масштабирует)
# Вместо попытки компенсировать масштабирование, мы рисуем круг в определении,
# и Sketchup сам правильно масштабирует его при любом трансформировании экземпляра
circle = defn_entities.add_circle(center_pt, normal_axis, radius)
circle.each { |e| e.set_attribute('ABFDrill', 'Type', type_tag) }
# 9. Добавляем CPoint
cpoint = defn_entities.add_cpoint(center_pt)
cpoint.set_attribute('ABFDrill', 'Type', type_tag)
return true
end
# --- ГЛАВНЫЙ ПРОЦЕСС ДЛЯ ПЕТЕЛЬ ---
def self.process_hinge_holes(count, diameter_mm, length_offset_mm, side_offset_mm, screw_diameter_mm, screw_spacing_mm, screw_vert_offset_mm)
model = Sketchup.active_model
selection = model.selection
items = selection.grep(Sketchup::ComponentInstance) + selection.grep(Sketchup::Group)
if items.empty?
UI.messagebox("Выберите один или несколько компонентов для установки петель.")
return
end
model.start_operation("ABF Style Add Hinges", true)
# Очищаем только петли на выделенных компонентах
items.each { |ent| self.cleanup_hinge_drill_geometry(ent) }
items.each do |entity|
self.apply_hinge_holes(entity, count.to_i, diameter_mm.mm, length_offset_mm.mm, side_offset_mm.mm, screw_diameter_mm.mm, screw_spacing_mm.mm, screw_vert_offset_mm.mm)
end
model.commit_operation
rescue => e
UI.messagebox("Ошибка при создании петель: #{e.message}")
model.abort_operation
end
# --- ЛОГИКА ДЛЯ СОЗДАНИЯ ОТВЕРСТИЙ ПОД ПЕТЛИ ---
def self.apply_hinge_holes(entity, count, diameter, length_offset, side_offset, screw_diameter, screw_spacing, screw_vert_offset)
defn = entity.respond_to?(:definition) ? entity.definition : entity.entities.parent
bounds = defn.bounds
# 1. Определяем оси компонента в локальных координатах
dims = [bounds.width, bounds.height, bounds.depth]
# Ось толщины (самая короткая) - Нормаль круга
min_dim = dims.min
thick_axis_idx = dims.index(min_dim)
thick_axis = Geom::Vector3d.new(0,0,0)
thick_axis[thick_axis_idx] = 1.0
# Ось длины (самая длинная) - Ось для распределения петель
max_dim = dims.max
long_axis_idx = dims.index(max_dim)
long_axis = Geom::Vector3d.new(0,0,0)
long_axis[long_axis_idx] = 1.0
# Ось ширины (средняя) - Ось для смещения 21.5мм и смещения саморезов
mid_dim = dims.sort[1]
mid_axis_idx = dims.index(mid_dim)
mid_axis = Geom::Vector3d.new(0,0,0)
mid_axis[mid_axis_idx] = 1.0
# 2. Определяем плоскость для отверстий (по центру толщины)
center_point = bounds.center.clone
# 3. Определяем начальную точку и направление (Вдоль длинной оси)
# Начальная координата для смещения по длине
start_coord_length = bounds.min[long_axis_idx]
offset_vec_length = long_axis.clone
offset_vec_length.length = length_offset
start_point_length = center_point.clone
start_point_length[long_axis_idx] = start_coord_length
start_point_length = start_point_length + offset_vec_length
# 4. Рассчитываем точки для всех петель (Вдоль длинной оси)
hole_points_length = []
length = max_dim
count = [1, count].max
if count == 1
hole_points_length << center_point
else
# Расстояние между центрами петель
remaining_length = length - (length_offset * 2)
if remaining_length < 0.mm
hole_points_length << center_point
else
spacing = remaining_length / (count - 1).to_f
(0...count).each do |i|
current_point = start_point_length + long_axis.clone.tap { |v| v.length = i * spacing }
hole_points_length << current_point
end
end
end
# 5. Применяем смещение по боковой оси (side_offset)
# Начальная координата по средней оси (от которой отсчитываем 21.5мм)
start_coord_side = bounds.min[mid_axis_idx]
# Вектор смещения по средней оси
side_offset_vec = mid_axis.clone
side_offset_vec.length = side_offset
# Точка, смещенная от края по средней оси
side_offset_point = center_point.clone
side_offset_point[mid_axis_idx] = start_coord_side
side_offset_point = side_offset_point + side_offset_vec
# Координата поверхности (max координата по оси толщины)
surface_coord = bounds.max[thick_axis_idx]
hole_points_length.each do |local_pt_length|
final_pt = local_pt_length.clone
# Устанавливаем координату по средней оси (смещение 21.5мм)
final_pt[mid_axis_idx] = side_offset_point[mid_axis_idx]
# Устанавливаем координату по оси толщины (на поверхность)
final_pt[thick_axis_idx] = surface_coord
# 1. Создаем отверстие под чашку (круг 35мм) - ИСПОЛЬЗУЕМ КОМПЕНСАЦИЮ
self.draw_drill_hole_geometry(entity, final_pt, diameter / 2.0, thick_axis, 'HingeHole')
# --- ЛОГИКА ДЛЯ ОТВЕРСТИЙ ПОД САМОРЕЗЫ ---
half_spacing = screw_spacing / 2.0
# Вектор смещения "выше чашки" (вдоль mid_axis)
shift_vec = mid_axis.clone
shift_vec.length = screw_vert_offset
# Базовые точки вдоль длинной оси (long_axis), центрированные на final_pt
pt1_base = final_pt - long_axis.clone.tap { |v| v.length = half_spacing }
pt2_base = final_pt + long_axis.clone.tap { |v| v.length = half_spacing }
# Применяем вертикальное смещение (shift_vec) к обеим точкам
pt1 = pt1_base + shift_vec
pt2 = pt2_base + shift_vec
[pt1, pt2].each do |screw_pt|
# Создаем отверстие под саморез (круг) - ИСПОЛЬЗУЕМ КОМПЕНСАЦИЮ
self.draw_drill_hole_geometry(entity, screw_pt, screw_diameter / 2.0, thick_axis, 'HingeHole')
end
# --- КОНЕЦ ЛОГИКИ САМОРЕЗОВ ---
end
end
# --- НОВЫЙ ГЛАВНЫЙ ПРОЦЕСС ДЛЯ ПЛАНКИ (ОБНОВЛЕНО) ---
# Изменено: hinge_count и hinge_offset_mm заменены на count и length_offset_mm
def self.process_strip_holes(diameter_mm, spacing_mm, side_offset_mm, count, length_offset_mm)
model = Sketchup.active_model
selection = model.selection
items = selection.grep(Sketchup::ComponentInstance) + selection.grep(Sketchup::Group)
if items.length != 1
UI.messagebox("Выберите ОДИН компонент для установки отверстий под планку.")
# Очищаем на всех выделенных, если их больше одного, или если ничего не выбрано
model.start_operation("ABF Strip Drill Cleanup", true)
items.each { |ent| self.cleanup_strip_drill_geometry(ent) }
model.commit_operation
return
end
entity = items.first
model.start_operation("ABF Style Add Strip Holes", true)
self.cleanup_strip_drill_geometry(entity) # Очистка перед созданием
# Передаем параметры для позиционирования
self.apply_strip_holes(entity, diameter_mm.mm, spacing_mm.mm, side_offset_mm.mm, count.to_i, length_offset_mm.mm)
model.commit_operation
rescue => e
UI.messagebox("Ошибка при создании отверстий под планку: #{e.message}")
model.abort_operation
end
# --- НОВАЯ ЛОГИКА ДЛЯ СОЗДАНИЯ ОТВЕРСТИЙ ПОД ПЛАНКУ (ОБНОВЛЕНО) ---
# Изменено: hinge_count и hinge_offset заменены на count и length_offset
def self.apply_strip_holes(entity, diameter, spacing, side_offset, count, length_offset)
defn = entity.respond_to?(:definition) ? entity.definition : entity.entities.parent
bounds = defn.bounds
# 1. Определяем оси компонента в локальных координатах
dims = [bounds.width, bounds.height, bounds.depth]
# Ось толщины (самая короткая) - Ось сверления (Normal)
min_dim = dims.min
thick_axis_idx = dims.index(min_dim)
thick_axis = Geom::Vector3d.new(0,0,0)
thick_axis[thick_axis_idx] = 1.0
# Ось длины (самая длинная) - Ось для распределения петель/планок
max_dim = dims.max
long_axis_idx = dims.index(max_dim)
long_axis = Geom::Vector3d.new(0,0,0)
long_axis[long_axis_idx] = 1.0
# Ось ширины (средняя) - Ось для смещения от края (Side Offset)
mid_dim = dims.sort[1]
mid_axis_idx = dims.index(mid_dim)
mid_axis = Geom::Vector3d.new(0,0,0)
mid_axis[mid_axis_idx] = 1.0
# 2. Расчет позиций центров планок вдоль длинной оси (long_axis)
center_point = bounds.center.clone
length = max_dim
count = [1, count].max
hole_points_length = [] # Это будут центры пар отверстий планки
if count == 1
# Если одна планка, то центр планки совпадает с центром компонента по длине
hole_points_length << center_point
else
# Начальная координата для смещения по длине (от короткого края)
start_coord_length = bounds.min[long_axis_idx]
offset_vec_length = long_axis.clone
offset_vec_length.length = length_offset # Используем новое смещение
start_point_length = center_point.clone
start_point_length[long_axis_idx] = start_coord_length
start_point_length = start_point_length + offset_vec_length
# Расстояние между центрами планок
remaining_length = length - (length_offset * 2) # Используем новое смещение
if remaining_length < 0.mm
hole_points_length << center_point
else
spacing_strip = remaining_length / (count - 1).to_f
(0...count).each do |i|
# current_point - это центр пары планки по длинной оси
current_point = start_point_length + long_axis.clone.tap { |v| v.length = i * spacing_strip }
hole_points_length << current_point
end
end
end
# 3. Определяем координаты для смещения 37мм (Side Offset)
# Начальная координата по средней оси (от которой отсчитываем 37мм)
start_coord_side = bounds.min[mid_axis_idx]
# Координата центра отверстий по средней оси (37мм от края)
side_coord = start_coord_side + side_offset
# 4. Определяем координату поверхности (по оси толщины)
# Отверстия сверлятся в пласть, поэтому берем max координату по оси толщины
surface_coord = bounds.max[thick_axis_idx]
# 5. Создаем точки и отверстия
half_spacing = spacing / 2.0 # Половина межосевого расстояния планки (32/2 = 16мм)
# hole_points_length - это центры пар планок
hole_points_length.each do |center_pt_long_axis|
# Координата центра пары отверстий по длинной оси
center_coord_length = center_pt_long_axis[long_axis_idx]
# --- НОВОЕ: Создание точки в центре между отверстиями планки ---
final_center_pt = Geom::Point3d.new(0, 0, 0)
final_center_pt[long_axis_idx] = center_coord_length
final_center_pt[mid_axis_idx] = side_coord
final_center_pt[thick_axis_idx] = surface_coord
cpoint = defn.entities.add_cpoint(final_center_pt)
cpoint.set_attribute('ABFDrill', 'Type', 'StripHole')
# --- КОНЕЦ НОВОГО БЛОКА ---
# Координаты центров отверстий по длинной оси (смещение +/- 16мм)
length_coord_1 = center_coord_length - half_spacing
length_coord_2 = center_coord_length + half_spacing
hole_coords_length = [length_coord_1, length_coord_2]
# Создаем пару отверстий
hole_coords_length.each do |length_coord|
final_pt = Geom::Point3d.new(0, 0, 0)
# Устанавливаем координаты
final_pt[long_axis_idx] = length_coord # Смещение +/- 16мм от центра
final_pt[mid_axis_idx] = side_coord # Смещение 37мм от края
final_pt[thick_axis_idx] = surface_coord # На поверхности
# Создаем отверстие - ИСПОЛЬЗУЕМ КОМПЕНСАЦИЮ
self.draw_drill_hole_geometry(entity, final_pt, diameter / 2.0, thick_axis, 'StripHole')
end
end
end
# --- МЕТОД: Аннотации (обновлен для включения StripHole) ---
def self.show_drill_annotations
model = Sketchup.active_model
entities = model.active_entities
selection = model.selection
model.start_operation('Проставить/Удалить Аннотации Присадок', true)
if @annotations_visible
self.cleanup_annotations(entities)
@annotations_visible = false
model.commit_operation
UI.messagebox("Аннотации размеров удалены.")
return
end
items = selection.grep(Sketchup::ComponentInstance) + selection.grep(Sketchup::Group)
if items.empty?
UI.messagebox("Выберите компоненты.")
model.abort_operation
return
end
self.cleanup_annotations(entities)
base_offset_distance = 50.mm
step_size = 50.mm
items.each do |entity|
bb = entity.bounds
bb_center = bb.center
defn_entities = entity.respond_to?(:definition) ? entity.definition.entities : entity.entities
# Общие размеры
overall_offset_y = -350.mm
start_pt_x = Geom::Point3d.new(bb.min.x, bb.min.y, bb.min.z)
end_pt_x = Geom::Point3d.new(bb.max.x, bb.min.y, bb.min.z)
offset_x = Geom::Vector3d.new(0, overall_offset_y, 0)
dim_overall_x = entities.add_dimension_linear(start_pt_x, end_pt_x, offset_x)
dim_overall_x.set_attribute('ABFDrill', 'Type', 'Dimension')
overall_offset_x = -350.mm
start_pt_y = Geom::Point3d.new(bb.min.x, bb.min.y, bb.min.z)
end_pt_y = Geom::Point3d.new(bb.min.x, bb.max.y, bb.min.z)
offset_y = Geom::Vector3d.new(overall_offset_x, 0, 0)
dim_overall_y = entities.add_dimension_linear(start_pt_y, end_pt_y, offset_y)
dim_overall_y.set_attribute('ABFDrill', 'Type', 'Dimension')
# Размеры до отверстий
# Собираем все точки присадки, петель и планки
drill_cpoints = defn_entities.grep(Sketchup::ConstructionPoint).select do |e|
type = e.get_attribute('ABFDrill', 'Type')
type == 'DrillHole' || type == 'HingeHole' || type == 'StripHole'
end
dimensions_to_place = []
drill_cpoints.each do |cpoint|
hole_pt = cpoint.position.transform(entity.transformation)
# X Dimension
dist_from_min_x = hole_pt.x - bb.min.x
dist_from_max_x = bb.max.x - hole_pt.x
if dist_from_min_x <= dist_from_max_x
start_pt_x = Geom::Point3d.new(bb.min.x, hole_pt.y, hole_pt.z)
value_x = dist_from_min_x
else
start_pt_x = Geom::Point3d.new(bb.max.x, hole_pt.y, hole_pt.z)
value_x = dist_from_max_x
end
direction_x = (hole_pt.y > bb_center.y) ? :Up : :Down
if value_x.abs > 0.001.mm
dimensions_to_place << { :type => :X, :value => value_x, :start_pt => start_pt_x, :end_pt => hole_pt, :direction => direction_x }
end
# Y Dimension
dist_from_min_y = hole_pt.y - bb.min.y
dist_from_max_y = bb.max.y - hole_pt.y
if dist_from_min_y <= dist_from_max_y
start_pt_y = Geom::Point3d.new(hole_pt.x, bb.min.y, hole_pt.z)
value_y = dist_from_min_y
else
start_pt_y = Geom::Point3d.new(hole_pt.x, bb.max.y, hole_pt.z)
value_y = dist_from_max_y
end
direction_y = (hole_pt.x > bb_center.x) ? :Right : :Left
if value_y.abs > 0.001.mm
dimensions_to_place << { :type => :Y, :value => value_y, :start_pt => start_pt_y, :end_pt => hole_pt, :direction => direction_y }
end
end
grouped_dims = dimensions_to_place.group_by { |d| d[:direction] }
step_counters = { :Up => 0, :Down => 0, :Right => 0, :Left => 0 }
grouped_dims.each do |direction, dims|
dims.sort_by! { |d| d[:value] }
dims.each do |d|
step = step_counters[direction]
offset_val = base_offset_distance + step * step_size
offset_vec = case direction
when :Up then Geom::Vector3d.new(0, offset_val, 0)
when :Down then Geom::Vector3d.new(0, -offset_val, 0)
when :Right then Geom::Vector3d.new(offset_val, 0, 0)
when :Left then Geom::Vector3d.new(-offset_val, 0, 0)
end
dim = entities.add_dimension_linear(d[:start_pt], d[:end_pt], offset_vec)
dim.set_attribute('ABFDrill', 'Type', 'Dimension')
step_counters[direction] += 1
end
end
end
@annotations_visible = true
model.commit_operation
UI.messagebox("Аннотации проставлены.")
rescue => e
UI.messagebox("Ошибка: #{e.message}")
model.abort_operation
end
# --- МЕТОД: Раскладка (без изменений) ---
def self.line_up_components
model = Sketchup.active_model
selection = model.selection
entities_to_line_up = selection.grep(Sketchup::ComponentInstance) + selection.grep(Sketchup::Group)
if entities_to_line_up.empty?
UI.messagebox("Выберите компоненты.")
return
end
model.start_operation('Разложить в линию', true)
begin
self.cleanup_annotations(model.active_entities)
@annotations_visible = false
entities_to_line_up.sort_by! do |e|
b = e.bounds
[b.width, b.height, b.depth].max
end
cursor_x = 0.0
gap = GAP
entities_to_line_up.each do |entity|
# Сброс трансформации (включая масштабирование) - это гарантирует,
# что круги, нарисованные в определении, будут выглядеть как круги.
entity.transformation = Geom::Transformation.new
bounds = entity.bounds
dims = [bounds.width, bounds.height, bounds.depth]
smallest_idx = dims.each_with_index.min[1]
rot_flat = Geom::Transformation.new
if smallest_idx == 0
rot_flat = Geom::Transformation.rotation(bounds.center, Geom::Vector3d.new(0, 1, 0), -90.degrees)
elsif smallest_idx == 1
rot_flat = Geom::Transformation.rotation(bounds.center, Geom::Vector3d.new(1, 0, 0), 90.degrees)
end
entity.transform!(rot_flat)
bounds = entity.bounds
rot_orient = Geom::Transformation.new
if bounds.width < bounds.height
rot_orient = Geom::Transformation.rotation(bounds.center, Geom::Vector3d.new(0, 0, 1), 90.degrees)
end
entity.transform!(rot_orient)
bounds = entity.bounds
move_vec = Geom::Vector3d.new(cursor_x - bounds.min.x, -bounds.min.y, -bounds.min.z)
entity.transform!(Geom::Transformation.translation(move_vec))
cursor_x = entity.bounds.max.x + gap
end
model.active_view.zoom(entities_to_line_up)
rescue => e
UI.messagebox("Ошибка: #{e.message}")
ensure
model.commit_operation
end
end
unless file_loaded?(__FILE__)
menu = UI.menu('Plugins')
menu.add_item('ABF Style Drill & Hinges') { self.show_dialog }
file_loaded(__FILE__)
end
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Why are these changes needed?
Related issue number
#203
Checks