cdpd 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cdpd/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ from .core import (
2
+ api_key,
3
+ model,
4
+ set,
5
+ set_api_key,
6
+ set_model,
7
+ get_model,
8
+ cdpd,
9
+ cd,
10
+ pd,
11
+ )
12
+
13
+ __all__ = [
14
+ "api_key",
15
+ "model",
16
+ "set",
17
+ "set_api_key",
18
+ "set_model",
19
+ "get_model",
20
+ "cdpd",
21
+ "cd",
22
+ "pd",
23
+ ]
24
+
25
+
26
+ def load_ipython_extension(ipython):
27
+ """Hỗ trợ load extension qua %load_ext cdpd."""
28
+ ipython.register_magic_function(cdpd, magic_kind="line")
29
+ ipython.register_magic_function(cd, magic_kind="cell")
30
+ ipython.register_magic_function(pd, magic_kind="cell")
cdpd/core.py ADDED
@@ -0,0 +1,165 @@
1
+ import os
2
+ import re
3
+ import httpx
4
+ from openai import OpenAI
5
+ from IPython import get_ipython
6
+ from IPython.core.magic import register_cell_magic, register_line_magic
7
+
8
+ DEFAULT_MODEL = "gemini-3.1-flash-lite"
9
+ RULE_PEP8 = "Executable Python code only. Zero markdown, comments, docstrings, test cases, or explanation."
10
+ SYSTEM_PROMPT_ANALYST = (
11
+ "You are an expert Data Analyst. Analyze the provided execution output and code directly "
12
+ "based on the user's request. Give concise, clear, and to-the-point insights formatted in clean Markdown. "
13
+ "Focus directly on answering the question accurately without unnecessary fluff."
14
+ )
15
+
16
+ api_key = None
17
+ model = DEFAULT_MODEL
18
+ _client = None
19
+
20
+
21
+ def set(key: str, model_name: str = None):
22
+ """Cú pháp rút gọn để cấu hình nhanh API key (và model nếu muốn).
23
+
24
+ Ví dụ:
25
+ cdpd.set("YOUR_API_KEY")
26
+ cdpd.set("YOUR_API_KEY", "gemini-3.1-flash-lite")
27
+ """
28
+ set_api_key(key)
29
+ if model_name:
30
+ set_model(model_name)
31
+
32
+
33
+ def set_api_key(key: str):
34
+ """Thiết lập API key cho Gemini / OpenAI client."""
35
+ global api_key, _client
36
+ api_key = key
37
+ _client = None # Reset client để khởi tạo lại với key mới khi dùng
38
+
39
+
40
+ def set_model(model_name: str):
41
+ """Thiết lập model Gemini mặc định (mặc định là 'gemini-3.1-flash-lite')."""
42
+ global model
43
+ if not model_name or not isinstance(model_name, str):
44
+ raise ValueError("Tên model phải là chuỗi ký tự hợp lệ.")
45
+ model = model_name.strip()
46
+
47
+
48
+ def get_model() -> str:
49
+ """Lấy tên model hiện tại đang được cấu hình."""
50
+ return model
51
+
52
+
53
+ def _get_client() -> OpenAI:
54
+ """Lấy hoặc khởi tạo client với API key đã được cấu hình hoặc từ biến môi trường."""
55
+ global _client
56
+ if _client is not None:
57
+ return _client
58
+
59
+ key = api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
60
+ if not key:
61
+ raise ValueError(
62
+ "API key chưa được thiết lập! Bạn có thể dùng:\n"
63
+ " - cdpd.set('YOUR_API_KEY')\n"
64
+ " - cdpd.api_key = 'YOUR_API_KEY'\n"
65
+ " - %cdpd YOUR_API_KEY\n"
66
+ " - hoặc biến môi trường `GEMINI_API_KEY`."
67
+ )
68
+
69
+ _client = OpenAI(
70
+ api_key=key,
71
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
72
+ http_client=httpx.Client(trust_env=False),
73
+ )
74
+ return _client
75
+
76
+
77
+ @register_line_magic
78
+ def cdpd(line):
79
+ """Line magic %cdpd để set nhanh API key trong notebook.
80
+
81
+ Ví dụ:
82
+ %cdpd YOUR_API_KEY
83
+ %cdpd YOUR_API_KEY gemini-3.1-flash-lite
84
+ """
85
+ parts = line.strip().split()
86
+ if not parts:
87
+ print("Vui lòng truyền API key: %cdpd YOUR_API_KEY [MODEL]")
88
+ return
89
+ set(parts[0], parts[1] if len(parts) > 1 else None)
90
+ print("✅ Đã cấu hình cdpd thành công!")
91
+
92
+
93
+ @register_cell_magic
94
+ def cd(line, cell):
95
+ """IPython cell magic %%cd để định dạng và chuẩn hóa code theo chuẩn PEP 8 bằng Gemini."""
96
+ client = _get_client()
97
+ model_to_use = line.strip() if line.strip() else model
98
+
99
+ res = client.chat.completions.create(
100
+ model=model_to_use,
101
+ messages=[
102
+ {"role": "system", "content": RULE_PEP8},
103
+ {"role": "user", "content": cell},
104
+ ],
105
+ temperature=0.0,
106
+ )
107
+ raw = res.choices[0].message.content.strip()
108
+ clean = re.sub(r"^```(?:python)?\s*|\s*```$", "", raw, flags=re.DOTALL).strip()
109
+
110
+ ipython = get_ipython()
111
+ if ipython is not None:
112
+ ipython.set_next_input(clean, replace=True)
113
+ return clean
114
+
115
+
116
+ @register_cell_magic
117
+ def pd(line, cell):
118
+ """IPython cell magic %%pd để đọc output của cell trước và in nhận xét dưới dạng text để copy vào Markdown."""
119
+ user_prompt = f"{line}\n{cell}".strip()
120
+ if not user_prompt:
121
+ user_prompt = "Hãy nhận xét ngắn gọn, súc tích và nêu các điểm chính từ kết quả / số liệu ở trên."
122
+
123
+ ipython = get_ipython()
124
+ last_output = None
125
+ last_code = None
126
+
127
+ if ipython is not None:
128
+ # Lấy biến `_` (output gần nhất của cell trước)
129
+ last_output = ipython.user_ns.get("_", None)
130
+
131
+ # Lấy code của cell trước đó
132
+ in_history = ipython.user_ns.get("_ih", [])
133
+ if len(in_history) >= 2:
134
+ last_code = in_history[-2]
135
+
136
+ context_parts = []
137
+ if last_code:
138
+ context_parts.append(f"### Code thực thi ở cell trước:\n```python\n{str(last_code).strip()}\n```")
139
+
140
+ if last_output is not None:
141
+ output_str = str(last_output)
142
+ if len(output_str) > 10000:
143
+ output_str = output_str[:10000] + "\n... [output truncated]"
144
+ context_parts.append(f"### Output / Kết quả nhận được:\n```text\n{output_str}\n```")
145
+
146
+ context_content = "\n\n".join(context_parts)
147
+
148
+ final_user_message = (
149
+ f"{context_content}\n\n### Yêu cầu nhận xét / Câu hỏi:\n{user_prompt}"
150
+ if context_parts
151
+ else user_prompt
152
+ )
153
+
154
+ client = _get_client()
155
+ res = client.chat.completions.create(
156
+ model=model,
157
+ messages=[
158
+ {"role": "system", "content": SYSTEM_PROMPT_ANALYST},
159
+ {"role": "user", "content": final_user_message},
160
+ ],
161
+ temperature=0.2,
162
+ )
163
+ answer = res.choices[0].message.content.strip()
164
+ # In ra dạng text bình thường để dễ dàng copy vào cell Markdown
165
+ print(answer)
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: cdpd
3
+ Version: 0.1.0
4
+ Summary: IPython cell magic tool: %%cd for code formatting and %%pd for AI output analysis and insights
5
+ Author-email: Nguyen <skyland1620@gmail.com>
6
+ License: MIT
7
+ Keywords: ipython,jupyter,gemini,pep8,cdpd,data-analysis,ai
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Framework :: IPython
12
+ Classifier: Framework :: Jupyter
13
+ Classifier: Topic :: Software Development :: Quality Assurance
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: openai>=1.0.0
18
+ Requires-Dist: httpx>=0.24.0
19
+ Requires-Dist: ipython>=7.0.0
20
+ Dynamic: license-file
21
+
22
+ # cdpd
23
+
24
+ Thư viện IPython / Jupyter Cell Magic hỗ trợ lập trình và phân tích dữ liệu với Google Gemini:
25
+ 1. **`%%pd`**: Tự động đọc output/kết quả từ cell trước đó và in nhận xét ngắn gọn, đủ ý dưới dạng văn bản để bạn dễ dàng copy dán vào các cell Markdown báo cáo.
26
+ 2. **`%%cd`**: Tự động định dạng, tối ưu và chuẩn hóa code trong cell theo chuẩn PEP 8.
27
+
28
+ ## 🚀 Cài đặt
29
+
30
+ ```bash
31
+ pip install cdpd
32
+ ```
33
+
34
+ ## ⚙️ Cấu hình (Cực kỳ ngắn gọn)
35
+
36
+ Bạn có thể cấu hình nhanh bằng một trong các cách sau:
37
+
38
+ ### Cách 1: Dùng hàm `cdpd.set()` (Khuyến nghị)
39
+ ```python
40
+ import cdpd
41
+
42
+ # Chỉ cần set key:
43
+ cdpd.set("YOUR_GEMINI_API_KEY")
44
+
45
+ # Hoặc set cả key lẫn model cùng lúc:
46
+ cdpd.set("YOUR_GEMINI_API_KEY", "gemini-3.1-flash-lite")
47
+ ```
48
+
49
+ ### Cách 2: Gán biến trực tiếp
50
+ ```python
51
+ import cdpd
52
+
53
+ cdpd.api_key = "YOUR_GEMINI_API_KEY"
54
+ cdpd.model = "gemini-3.1-flash-lite" # (tùy chọn)
55
+ ```
56
+
57
+ ### Cách 3: Dùng Line Magic `%cdpd` trực tiếp trong Notebook
58
+ ```python
59
+ import cdpd
60
+
61
+ %cdpd YOUR_GEMINI_API_KEY
62
+ ```
63
+
64
+ ### Cách 4: Qua biến môi trường
65
+ ```bash
66
+ export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"
67
+ ```
68
+
69
+ ---
70
+
71
+ ## 📖 Hướng dẫn sử dụng
72
+
73
+ ### 1. Phân tích & Nhận xét số liệu (`%%pd`)
74
+
75
+ Sau khi chạy 1 cell sinh ra số liệu, biểu đồ hoặc DataFrame:
76
+
77
+ ```python
78
+ # [Cell 1 - Code tính toán]
79
+ df.describe()
80
+ ```
81
+
82
+ Mở cell code mới ngay bên dưới để hỏi nhận xét:
83
+
84
+ ```python
85
+ # [Cell 2]
86
+ %%pd
87
+ Nhận xét về độ lệch chuẩn và các giá trị bất thường của bảng số liệu trên.
88
+ ```
89
+
90
+ > 💡 **Kết quả:** Gemini sẽ in nhận xét dạng text thuần. Bạn chỉ cần bôi đen, copy và dán vào cell Markdown để làm báo cáo/thuyết minh.
91
+
92
+ ---
93
+
94
+ ### 2. Chuẩn hóa & Format code (`%%cd`)
95
+
96
+ Thêm `%%cd` ở dòng đầu của cell code cần format:
97
+
98
+ ```python
99
+ %%cd
100
+ def tinh_tong( a,b ):
101
+ x=a+b;return x
102
+ ```
103
+
104
+ ---
105
+
106
+ ## 📄 License
107
+
108
+ MIT License. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,7 @@
1
+ cdpd/__init__.py,sha256=XoY4q8h3XokUwBmxRh8bD-LSuonJLUb_fiBYbMDZ_fs,541
2
+ cdpd/core.py,sha256=fz-z5rno6lr-tvbZF8F-Bqrr3tFFdh6NxQNweMn1ffI,5544
3
+ cdpd-0.1.0.dist-info/licenses/LICENSE,sha256=ESYyLizI0WWtxMeS7rGVcX3ivMezm-HOd5WdeOh-9oU,1056
4
+ cdpd-0.1.0.dist-info/METADATA,sha256=Sl8XPKzWRqPCILpmCNmKcRwQ3QTNE3mXfEMF5fx93xY,2925
5
+ cdpd-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
6
+ cdpd-0.1.0.dist-info/top_level.txt,sha256=YJHtlzD32ayW1rQwqwoqrs6BB1fCg9Lp_ouoE4S7X-U,5
7
+ cdpd-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ cdpd