Skip to content

Commit 98eb3d7

Browse files
author
Yuen Sze Hong
committed
Changelog:
- fixed #7 - Added dotenv support - Added playground.py - Added __main__.py for directly running the package - Added Custom Seed feature - Updated docs
1 parent 9171576 commit 98eb3d7

File tree

8 files changed

+378
-174
lines changed

8 files changed

+378
-174
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ cookie.json
1717
notes.txt
1818
todolist.txt
1919
images/
20+
.env

README.md

Lines changed: 79 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,97 @@
11
# Microsoft Designer API
22

3+
A Python library for generating images using Microsoft Designer's API.
4+
35
### Installation
46

5-
```$ pip3 install microsoftdesigner```
7+
```bash
8+
pip install microsoftdesigner
9+
```
610

7-
### Usage
11+
### Configuration
812

9-
```
10-
$ python3 -m microsoftdesigner -h
11-
12-
options:
13-
-h, --help show this help message and exit
14-
--user_id USER_ID User ID
15-
--auth_token AUTH_TOKEN
16-
Auth Token
17-
--prompt PROMPT Prompt
18-
--save_path FILE_PATH
19-
File Path to save the output (optional)
20-
--file_name FILE_NAME
21-
File Name to save the output (optional)
22-
--resolution RESOLUTION
23-
Resolution of the image (optional)
24-
(default: 1024x1024, available: 1024x1792, 1792x1024)
13+
Create a `.env` file in your project root with:
2514

15+
```env
16+
USER_ID=your_user_id_here
17+
AUTH_TOKEN=your_auth_token_here
2618
```
27-
## Getting Started
28-
- Create a new user account or login [Microsoft Designer](https://designer.microsoft.com/)
29-
- Open the developer tools and go to the network tab
30-
- Create a new image using random text
31-
- Find the request with post method and copy the request headers
32-
- Copy the user id, auth token (Authorization: value) from the request headers
33-
- Run the script with the copied values
34-
- Note: **auth_token will expire after 24 hours**
35-
- Note: **Do not pass resolution other than 1024x1024, 1024x1792, 1792x1024**
19+
20+
### Command Line Usage
3621

3722
```bash
38-
$ python3 -m microsoftdesigner --user_id <user_id> --auth_token <auth_token> --prompt <prompt> --resolution <resolution> --save_path <save_path>
23+
python -m microsoftdesigner --help
3924

25+
options:
26+
-h, --help show this help message and exit
27+
--user_id USER_ID User ID (or set MSDESIGNER_USER_ID env var)
28+
--auth_token AUTH_TOKEN
29+
Authentication token (or set MSDESIGNER_AUTH_TOKEN env var)
30+
--prompt PROMPT Image generation prompt
31+
--save_path SAVE_PATH
32+
Path to save generated images (default: images)
33+
--resolution {1024x1024,1024x1792,1792x1024}
34+
Image resolution (default: 1024x1024)
35+
--boost_count BOOST_COUNT
36+
Boost count for generation quality (default: 1)
37+
--seed SEED Random seed for reproducible results (optional)
4038
```
41-
### **Python Example**
4239

40+
### Python Usage
41+
42+
Basic example:
4343
```python
4444
from microsoftdesigner.gen_images import create_img
45-
create_img(user_id, auth_token, prompt, resolution)
45+
from dotenv import load_dotenv
46+
import os
47+
48+
load_dotenv() # Load environment variables from .env file
49+
50+
# Get credentials from environment
51+
user_id = os.getenv("USER_ID")
52+
auth_token = os.getenv("AUTH_TOKEN")
53+
54+
# Generate images
55+
image_paths = create_img(
56+
user_id=user_id,
57+
auth_token=auth_token,
58+
prompt="a beautiful sunset over mountains",
59+
save_path="images", # Optional: defaults to 'images'
60+
resolution="1024x1024", # Optional: 1024x1024, 1024x1792, 1792x1024
61+
boost_count=1, # Optional: enhance generation quality (default: 1)
62+
seed=42 # Optional: set for reproducible results
63+
)
4664

47-
# Image will be saved in images folder
65+
# Example output: list of paths like
66+
# ['images/1024x1024/123e4567-e89b-12d3-a456-426614174000.jpg',
67+
# 'images/1024x1024/987fcdeb-51d3-12d3-a456-426614174000.jpg', ...]
68+
print(f"Generated images saved to: {image_paths}")
4869
```
4970

71+
## Getting Started
72+
73+
1. Create/login to your [Microsoft Designer](https://designer.microsoft.com/) account
74+
2. Open browser developer tools (F12) and go to Network tab
75+
3. Generate an image using any prompt in Microsoft Designer
76+
4. In the Network tab, find the POST request to `/DallE.ashx`
77+
5. From the request headers, copy:
78+
- `UserId` header value → set as USER_ID
79+
- `Authorization` header value → set as AUTH_TOKEN
80+
6. Save these values in your .env file or pass them directly to the API
81+
82+
### Important Notes
83+
84+
- **Authentication**: Auth tokens expire after 24 hours - you'll need to refresh them
85+
- **Resolutions**: Only use supported resolutions:
86+
- Square: 1024x1024
87+
- Portrait: 1024x1792
88+
- Widescreen: 1792x1024
89+
- **File Organization**: Generated images are automatically saved in resolution-specific subfolders:
90+
```
91+
images/
92+
├── 1024x1024/
93+
├── 1024x1792/
94+
└── 1792x1024/
95+
```
96+
- **Error Handling**: The API will return an empty list if you've run out of credits (403 error)
97+

playground.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import os
2+
from typing import Dict, Literal
3+
from microsoftdesigner.gen_images import create_img
4+
from dotenv import load_dotenv
5+
6+
load_dotenv()
7+
8+
ResolutionType = Literal['square', 'widescreen', 'portrait']
9+
10+
RESOLUTIONS: Dict[ResolutionType, str] = {
11+
'square': '1024x1024',
12+
'portrait': '1024x1792',
13+
'widescreen': '1792x1024' # Fixed typo in 'portrait'
14+
}
15+
16+
ACTIONS = [
17+
"sitting",
18+
"riding",
19+
"laying",
20+
]
21+
22+
PROMPTS = [f"anime girl {action} on an exercise ball in a room with exercise balls" for action in ACTIONS ]
23+
24+
DEFAULT_NUM_IMAGES = 40
25+
26+
def generate_images(
27+
prompt: str,
28+
resolution_type: ResolutionType = 'widescreen',
29+
) -> None:
30+
"""
31+
Generate images using Microsoft Designer API.
32+
33+
Args:
34+
prompt: The text prompt for image generation
35+
resolution_type: Type of resolution from RESOLUTIONS
36+
num_images: Number of images to generate
37+
"""
38+
user_id = os.getenv("USER_ID")
39+
auth_token = os.getenv("AUTH_TOKEN")
40+
41+
if not user_id or not auth_token:
42+
raise ValueError("USER_ID and AUTH_TOKEN must be set in .env file")
43+
44+
# for _ in range(num_images):
45+
resolution = RESOLUTIONS[resolution_type]
46+
create_img(user_id, auth_token, prompt, resolution=resolution)
47+
48+
if __name__ == "__main__":
49+
prompt = PROMPTS[1]
50+
generate_images(prompt)

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ dependencies = [
2424
"httpx>=0.28.1",
2525
"beautifulsoup4>=4.12.3",
2626
"lxml>=5.3",
27+
"python-dotenv",
2728
]
2829

2930
[project.urls]
3031
Homepage = "https://github.com/imnotdev25/Msdesigner-api"
3132
Issues = "https://github.com/imnotdev25/Msdesigner-api/issues"
32-

src/microsoftdesigner/__main__.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import os
2+
import argparse
3+
import sys
4+
from venv import logger
5+
from dotenv import load_dotenv
6+
from microsoftdesigner.constants import VALID_RESOLUTIONS
7+
from microsoftdesigner.gen_images import create_img
8+
9+
load_dotenv()
10+
11+
parser = argparse.ArgumentParser(description="Generate images using Microsoft Designer API")
12+
parser.add_argument(
13+
"--user_id",
14+
required=False,
15+
help="User ID",
16+
default=os.getenv("MSDESIGNER_USER_ID"),
17+
)
18+
parser.add_argument(
19+
"--auth_token",
20+
required=False,
21+
help="Authentication token",
22+
default=os.getenv("MSDESIGNER_AUTH_TOKEN"),
23+
)
24+
parser.add_argument("--prompt", required=True, help="Image generation prompt")
25+
parser.add_argument("--save_path", default="images", help="Path to save generated images")
26+
parser.add_argument(
27+
"--resolution",
28+
default="1024x1024",
29+
choices=VALID_RESOLUTIONS,
30+
help="Image resolution",
31+
)
32+
parser.add_argument(
33+
"--boost_count", type=int, default=1, help="Boost count"
34+
)
35+
parser.add_argument(
36+
"--seed",
37+
type=int,
38+
default=None,
39+
help="Seed for reproducible generations (random if not provided)",
40+
)
41+
42+
args = parser.parse_args()
43+
44+
user_id = args.user_id
45+
auth_token = args.auth_token
46+
47+
if not user_id:
48+
parser.error(
49+
"Please provide --user_id argument or set MSDESIGNER_USER_ID environment variable."
50+
)
51+
if not auth_token:
52+
parser.error(
53+
"Please provide --auth_token argument or set MSDESIGNER_AUTH_TOKEN environment variable."
54+
)
55+
56+
try:
57+
image_paths = create_img(
58+
user_id,
59+
auth_token,
60+
args.prompt,
61+
save_path=args.save_path,
62+
resolution=args.resolution,
63+
boost_count=args.boost_count,
64+
seed=args.seed,
65+
)
66+
logger.info(f"Generated images saved to: {image_paths}")
67+
except Exception as e:
68+
logger.error(f"Failed to generate images: {str(e)}")
69+
sys.exit(1)

src/microsoftdesigner/constants.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,28 @@
11
import uuid
22

3+
# Base URL for Microsoft Designer's DALL-E API
34
MS_BASE_URL = "https://designerapp.officeapps.live.com/designerapp/DallE.ashx"
45

5-
HEADERS = {'Host': 'designerapp.officeapps.live.com',
6+
# Default headers for API requests
7+
HEADERS = {
8+
'Host': 'designerapp.officeapps.live.com',
69
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0',
7-
'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'en-US,en;q=0.5',
8-
'Accept-Encoding': 'gzip, deflate, br, zstd', 'Referer': 'https://designer.microsoft.com/',
9-
'ClientId': f'{str(uuid.uuid4())}', 'ContainerId': f'{str(uuid.uuid4())}', 'SessionId': f'{str(uuid.uuid4())}',
10-
'HostApp': 'DesignerApp', 'ClientName': 'DesignerApp', 'Origin': 'https://designer.microsoft.com',
11-
'Connection': 'keep-alive', 'FileToken': f'{str(uuid.uuid4())}', }
10+
'Accept': 'application/json, text/plain, */*',
11+
'Accept-Language': 'en-US,en;q=0.5',
12+
'Accept-Encoding': 'gzip, deflate, br, zstd',
13+
'Referer': 'https://designer.microsoft.com/',
14+
'ClientId': f'{str(uuid.uuid4())}',
15+
'ContainerId': f'{str(uuid.uuid4())}',
16+
'SessionId': f'{str(uuid.uuid4())}',
17+
'HostApp': 'DesignerApp',
18+
'ClientName': 'DesignerApp',
19+
'Origin': 'https://designer.microsoft.com',
20+
'Connection': 'keep-alive',
21+
'FileToken': f'{str(uuid.uuid4())}',
22+
}
1223

24+
# Query parameters for the API endpoint
1325
PARAMS = {'action': 'GetDallEImagesCogSci'}
26+
27+
# Valid resolutions
28+
VALID_RESOLUTIONS = {'1024x1024', '1024x1792', '1792x1024'}

0 commit comments

Comments
 (0)