├── API
├── example.html
└── server.py
├── LICENSE
├── README.md
├── cli
└── cli.py
├── login.py
└── requirements.txt
/API/example.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Chat and TTS
7 |
8 |
9 | PuterAi-python_SDK
10 |
11 |
12 |
13 |
14 |
15 |
16 | Response
17 |
18 |
19 | Generate Text to Speech
20 |
21 |
22 |
23 |
24 |
25 | Play TTS
26 |
27 |
28 |
59 |
60 |
--------------------------------------------------------------------------------
/API/server.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, jsonify, request, send_file
2 | from flask_cors import CORS
3 | import requests
4 | from io import BytesIO
5 | from dotenv import load_dotenv
6 | import os
7 |
8 | load_dotenv()
9 |
10 | app = Flask(__name__)
11 | CORS(app)
12 |
13 | url = 'https://api.puter.com/drivers/call'
14 | headers = {
15 | 'Accept': '*/*',
16 | 'Accept-Language': 'en-US,en;q=0.9',
17 | 'Authorization': f"Bearer {os.getenv('API_TOKEN')}",
18 | 'Connection': 'keep-alive',
19 | 'Content-Type': 'application/json;charset=UTF-8',
20 | 'Origin': 'https://docs.puter.com',
21 | 'Referer': 'https://docs.puter.com/',
22 | 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36',
23 | }
24 |
25 | conversation_history = []
26 |
27 | def mowhn(message):
28 | conversation_history.append({"content": message})
29 | data = {
30 | "interface": "puter-chat-completion",
31 | "driver": "openai-completion",
32 | "method": "complete",
33 | "args": {
34 | "messages": conversation_history
35 | }
36 | }
37 |
38 | response = requests.post(url, headers=headers, json=data)
39 |
40 | if response.status_code == 200:
41 | response_json = response.json()
42 | if response_json.get("success"):
43 | bot_reply = response_json['result']['message']['content']
44 | conversation_history.append({"content": bot_reply, "role": "assistant"})
45 | return bot_reply
46 | return "Failed to get a valid response from the API."
47 | return f"Request failed with status code {response.status_code}"
48 |
49 | def puter(user_text):
50 | data = {
51 | "interface": "puter-tts",
52 | "driver": "aws-polly",
53 | "method": "synthesize",
54 | "args": {
55 | "text": user_text
56 | }
57 | }
58 |
59 | response = requests.post(url, json=data, headers=headers)
60 |
61 | if response.status_code == 200:
62 | return BytesIO(response.content)
63 | return None
64 |
65 | @app.route('/chat', methods=['POST'])
66 | def chat():
67 | user_input = request.json.get('message')
68 | if user_input:
69 | bot_response = mowhn(user_input)
70 | return jsonify({'response': bot_response})
71 | return jsonify({'error': 'No message provided'}), 400
72 |
73 | @app.route('/tts', methods=['POST'])
74 | def tts():
75 | user_text = request.json.get('text')
76 | if user_text:
77 | audio_data = puter(user_text)
78 | if audio_data:
79 | return send_file(audio_data, mimetype='audio/mp3', as_attachment=False)
80 | return jsonify({'error': 'Failed to generate TTS'}), 500
81 | return jsonify({'error': 'No text provided'}), 400
82 |
83 | if __name__ == '__main__':
84 | app.run(debug=True)
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 mr_mowhn
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.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # PuterAi-python_SDK
3 |
4 | PuterAi Python SDK provides a simple way to interact with the Puter AI API for chatbot interactions and text-to-speech (TTS) generation. This SDK allows you to integrate chatbot and TTS functionalities into your own applications.
5 |
6 | ## Features
7 |
8 | - **Chatbot Interaction**: Communicate with a chatbot powered by Puter AI.
9 | - **Text-to-Speech (TTS)**: Convert any text into audio using AWS Polly TTS service.
10 |
11 | ## Project Structure
12 |
13 | The project consists of multiple components:
14 |
15 | - **`login.py`**: Script to handle user login and retrieve an API token for further requests.
16 | - **`cli.py`**: Command-line interface that allows users to interact with the Puter chatbot or generate TTS output.
17 | - **`server.py`**: A Flask-based API server that exposes endpoints for chatbot and TTS functionalities.
18 | - **`example.html`**: A simple HTML front-end to interact with the chatbot and generate TTS via a browser.
19 |
20 | ## Requirements
21 |
22 | To run this project, you need to install the following dependencies:
23 |
24 | - `requests`: To handle HTTP requests.
25 | - `flask`: For the API server.
26 | - `flask_cors`: For handling Cross-Origin Resource Sharing (CORS).
27 | - `dotenv`: To load environment variables from a .env file.
28 |
29 | You can install the required dependencies with:
30 |
31 | ```bash
32 | pip install -r requirements.txt
33 | ```
34 |
35 | ## Setup Instructions
36 |
37 | 1. **Clone the Repository**
38 |
39 | ```bash
40 | git clone https://github.com/mowhn/PuterAi-python_SDK.git
41 | cd puterAi-python_SDK
42 | ```
43 |
44 | 2. **Setup .env File in Both CLI and API Folders**
45 |
46 | Create a `.env` file in both the `cli` and `API` directories and include your API_TOKEN:
47 |
48 | ```env
49 | API_TOKEN=your_api_token_here
50 | ```
51 |
52 | 3. **Get the API Token**
53 |
54 | To quickly obtain your `API_TOKEN`, you must first run `login.py` to log in and retrieve the token:
55 |
56 | - Run `login.py`:
57 |
58 | ```bash
59 | cd cli
60 | python login.py
61 | ```
62 |
63 | This will prompt you for your username and password, and if the login is successful, it will output the `API_TOKEN`. You can copy this token and paste it into the `.env` file in both the `cli` and `API` folders.
64 |
65 | **Note**: If you don't have a Puter AI account, you can sign up at
66 |
67 |
68 |
69 | 4. **Running the Project**
70 |
71 | - Run the API Server:
72 |
73 | ```bash
74 | cd API
75 | python server.py
76 | ```
77 |
78 | This will start the Flask API server on `http://localhost:5000`.
79 |
80 | - Use the Command-Line Interface (CLI):
81 |
82 | To interact with the chatbot or generate TTS from the command line, run:
83 |
84 | ```bash
85 | cd cli
86 | python cli.py
87 | ```
88 |
89 | 5. **Front-End Example**
90 |
91 | Open the `example.html` file in a browser to interact with the Puter chatbot and generate TTS:
92 |
93 | - **Chat with the Bot**: Enter a message and receive a response from the bot.
94 | - **Generate TTS**: Enter text to convert into speech, and play the generated audio.
95 |
96 | ## Endpoints
97 |
98 | The Flask API exposes the following endpoints:
99 |
100 | - **POST `/chat`**: Accepts a JSON object with a `message` field and returns a bot response.
101 |
102 | Example request:
103 |
104 | ```json
105 | {
106 | "message": "Hello, bot!"
107 | }
108 | ```
109 |
110 | - **POST `/tts`**: Accepts a JSON object with a `text` field and returns the corresponding TTS audio.
111 |
112 | Example request:
113 |
114 | ```json
115 | {
116 | "text": "Hello, this is a test."
117 | }
118 | ```
119 |
120 |
121 | ## License
122 |
123 | This project is licensed under the MIT License - see the [LICENSE](https://github.com/mowhn/PuterAi-python_SDK/blob/main/LICENSE) file for details.
124 |
125 | ---
126 |
127 | Enjoy building with Puter!
128 |
--------------------------------------------------------------------------------
/cli/cli.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | from dotenv import load_dotenv
4 | import os
5 |
6 | load_dotenv()
7 |
8 | url = 'https://api.puter.com/drivers/call'
9 | headers = {
10 | 'Accept': '*/*',
11 | 'Accept-Language': 'en-US,en;q=0.9',
12 | 'Authorization': f"Bearer {os.getenv('API_TOKEN')}",
13 | 'Connection': 'keep-alive',
14 | 'Content-Type': 'application/json;charset=UTF-8',
15 | 'Origin': 'https://docs.puter.com',
16 | 'Referer': 'https://docs.puter.com/',
17 | 'Sec-Fetch-Dest': 'empty',
18 | 'Sec-Fetch-Mode': 'cors',
19 | 'Sec-Fetch-Site': 'same-site',
20 | 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36',
21 | 'sec-ch-ua': '"Not-A.Brand";v="99", "Chromium";v="124"',
22 | 'sec-ch-ua-mobile': '?1',
23 | 'sec-ch-ua-platform': '"Android"',
24 | }
25 |
26 | conversation_history = []
27 |
28 | def mowhn(message):
29 | conversation_history.append({"content": message})
30 | data = {
31 | "interface": "puter-chat-completion",
32 | "driver": "openai-completion",
33 | "test_mode": False,
34 | "method": "complete",
35 | "args": {
36 | "messages": conversation_history
37 | }
38 | }
39 | response = requests.post(url, headers=headers, json=data)
40 | if response.status_code == 200:
41 | response_json = response.json()
42 | if response_json.get("success"):
43 | bot_reply = response_json['result']['message']['content']
44 | conversation_history.append({"content": bot_reply, "role": "assistant"})
45 | return bot_reply
46 | else:
47 | return "Failed to get a valid response from the API."
48 | else:
49 | return f"Request failed with status code {response.status_code}"
50 |
51 | def puter(user_text):
52 | data = {
53 | "interface": "puter-tts",
54 | "driver": "aws-polly",
55 | "test_mode": False,
56 | "method": "synthesize",
57 | "args": {
58 | "text": user_text
59 | }
60 | }
61 | response = requests.post(url, json=data, headers=headers)
62 | if response.status_code == 200:
63 | with open('output_file.mp3', 'wb') as file:
64 | file.write(response.content)
65 | print("MP3 file has been saved as 'output_file.mp3'.")
66 | else:
67 | print(f"Failed to retrieve the file. Status code: {response.status_code}")
68 |
69 | def mowhn_chat():
70 | print("Chatbot: Hello! How can I assist you today?")
71 | while True:
72 | user_input = input("You: ")
73 | if user_input.lower() == "exit":
74 | print("Chatbot: Goodbye!")
75 | break
76 | bot_response = mowhn(user_input)
77 | print(f"Chatbot: {bot_response}")
78 |
79 | def main():
80 | print("Welcome! Please choose an option:")
81 | print("1. Chat")
82 | print("2. Generate Text to Speech (TTS)")
83 | choice = input("Enter the number of your choice: ")
84 | if choice == "1":
85 | mowhn_chat()
86 | elif choice == "2":
87 | user_text = input("Enter the text you want to synthesize: ")
88 | puter(user_text)
89 | else:
90 | print("Invalid choice. Please select either 1 or 2.")
91 |
92 | main()
--------------------------------------------------------------------------------
/login.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | def mowhn():
5 | username = input("Enter your username: ")
6 | password = input("Enter your password: ")
7 |
8 | url = "https://puter.com/login"
9 | headers = {
10 | "Accept": "*/*",
11 | "Accept-Language": "en-US,en;q=0.9",
12 | "Connection": "keep-alive",
13 | "Content-Type": "application/json",
14 | "Origin": "https://puter.com",
15 | "Referer": "https://puter.com/",
16 | "User-Agent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36",
17 | }
18 |
19 | payload = {
20 | "username": username,
21 | "password": password
22 | }
23 |
24 | try:
25 | response = requests.post(url, headers=headers, json=payload)
26 |
27 | if response.status_code == 200:
28 | data = response.json()
29 | if data.get("proceed"):
30 | print(f"Login successful! Token: {data['token']}")
31 | else:
32 | print("Login failed. Please check your credentials.")
33 | else:
34 | print(f"Error: Received status code {response.status_code}")
35 | except Exception as e:
36 | print(f"An error occurred: {e}")
37 |
38 | if __name__ == "__main__":
39 | mowhn()
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | Flask
2 | flask-cors
3 | requests
4 | python-dotenv
--------------------------------------------------------------------------------