-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenrouter_web_tonegenerator.py
190 lines (166 loc) · 6.5 KB
/
openrouter_web_tonegenerator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import os
import requests
import re
import gradio as gr
import time
from dotenv import load_dotenv
from collections import deque
from threading import Lock
# Load environment variables from .env file
load_dotenv()
# OpenRouter API configuration
API_URL = "https://openrouter.ai/api/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ.get('OPENROUTER_API_KEY')}",
"HTTP-Referer": "https://github.com/your-username/your-repo",
"X-Title": "OpenRouter Tone Generator",
"Content-Type": "application/json"
}
MODEL = "deepseek/deepseek-chat:free"
# Rate limiter settings
MAX_REQUESTS_PER_MINUTE = 10
MAX_REQUESTS_PER_DAY = 100
MINUTE_WINDOW = 60 # seconds
DAY_WINDOW = 24 * 60 * 60 # seconds (24 hours)
minute_timestamps = deque()
day_timestamps = deque()
rate_limit_lock = Lock()
# Set page title and description
title = "AI Tone Generator"
description = """
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
<div>
<p>Transform your text into different tones using the Deepseek V3 model via OpenRouter API. Select a tone and paste your text to get started!</p>
<p><small>Note: This service is rate-limited to {MAX_REQUESTS_PER_MINUTE} requests per minute and {MAX_REQUESTS_PER_DAY} requests per day.</small></p>
</div>
</div>
""".format(
MAX_REQUESTS_PER_MINUTE=MAX_REQUESTS_PER_MINUTE,
MAX_REQUESTS_PER_DAY=MAX_REQUESTS_PER_DAY
)
def is_rate_limited():
"""Check if the current request would exceed the rate limit"""
with rate_limit_lock:
now = time.time()
# Check minute limit
while minute_timestamps and now - minute_timestamps[0] > MINUTE_WINDOW:
minute_timestamps.popleft()
if len(minute_timestamps) >= MAX_REQUESTS_PER_MINUTE:
return "Rate limit exceeded. Please wait a minute before trying again."
# Check daily limit
while day_timestamps and now - day_timestamps[0] > DAY_WINDOW:
day_timestamps.popleft()
if len(day_timestamps) >= MAX_REQUESTS_PER_DAY:
return "Daily limit reached. Please try again tomorrow."
# Add current timestamp to both queues
minute_timestamps.append(now)
day_timestamps.append(now)
return False
def get_tone_description(tone):
"""Get the description and example for each tone"""
tone_descriptions = {
"playful": "fun and lighthearted, using casual language and maybe even some wordplay",
"serious": "formal and grave, emphasizing importance and gravity",
"formal": "professional and proper, using business etiquette and formal vocabulary",
"casual": "relaxed and informal, like talking to a friend",
"professional": "business-appropriate, maintaining clarity and professionalism",
"friendly": "warm and approachable, like chatting with a close friend",
"enthusiastic": "energetic and excited, using upbeat language and positive expressions",
"sarcastic": "subtly humorous with a touch of irony and wit",
"poetic": "flowery and descriptive, using metaphors and vivid language",
"technical": "precise and technical, focusing on accuracy and specificity"
}
return tone_descriptions.get(tone, "neutral")
def generate_tone_variation(text, tone):
"""Generate a tone variation using the OpenRouter API"""
try:
# Check rate limit
rate_limit_status = is_rate_limited()
if rate_limit_status:
return rate_limit_status
# Get tone description
tone_style = get_tone_description(tone)
# Create the system message and user prompt
system_message = f"""You are an expert at rewriting text in different tones.
Your task is to rewrite the given text in a {tone} tone ({tone_style})."""
user_prompt = f"""Please rewrite this text in a {tone} tone:
{text}
Make it {tone_style}"""
# Make API request
response = requests.post(
API_URL,
headers=HEADERS,
json={
"model": MODEL,
"messages": [
{"role": "system", "content": system_message},
{"role": "user", "content": user_prompt}
],
"temperature": 0.7,
"max_tokens": 1000
},
timeout=60
).json()
# Check for errors
if "error" in response:
return f"API Error: {response['error']['message']}"
# Extract and clean the response
generated_text = response['choices'][0]['message']['content']
return generated_text.strip()
except Exception as e:
return f"Error: {str(e)}"
# Create the Gradio interface
with gr.Blocks(theme="soft") as demo:
gr.Markdown(f"# {title}")
gr.Markdown(description)
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
label="Enter your text",
placeholder="Type or paste your text here...",
lines=5
)
tone_dropdown = gr.Dropdown(
choices=[
"playful",
"serious",
"formal",
"casual",
"professional",
"friendly",
"enthusiastic",
"sarcastic",
"poetic",
"technical"
],
label="Select tone",
value="formal"
)
generate_btn = gr.Button("Generate Tone Variation")
with gr.Column():
output = gr.Textbox(
label="Modified text",
lines=5,
interactive=False
)
# Example inputs
gr.Examples(
examples=[
["The meeting is scheduled for tomorrow at 2 PM.", "casual"],
["I love this new restaurant!", "formal"],
["The project deadline is approaching.", "playful"],
["The weather is beautiful today.", "poetic"],
["Your appointment is on June 1st at 4:30 PM.", "friendly"],
["The system requires 16GB of RAM.", "technical"]
],
inputs=[text_input, tone_dropdown]
)
generate_btn.click(
fn=generate_tone_variation,
inputs=[text_input, tone_dropdown],
outputs=output
)
# Launch the app
if __name__ == "__main__":
print("Starting OpenRouter Tone Generator...")
demo.launch(share=True) # Set share=False if you don't want to create a public link