-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-server.py
More file actions
executable file
·167 lines (139 loc) · 6.1 KB
/
Copy pathsimple-server.py
File metadata and controls
executable file
·167 lines (139 loc) · 6.1 KB
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
#!/usr/bin/env python3
"""
Simple Python server for Tweet Reply Generator
Use this if you don't have Node.js installed yet
"""
import http.server
import socketserver
import json
import urllib.request
import urllib.parse
import os
from urllib.parse import urlparse, parse_qs
PORT = 3000
API_KEY = "your_openrouter_api_key_here" # Replace with your actual API key
class TweetReplyHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory="public", **kwargs)
def do_POST(self):
if self.path == '/api/analyze' or self.path == '/api/generate-reply':
self.handle_api_request()
else:
self.send_error(404)
def handle_api_request(self):
try:
# Read request body
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))
if API_KEY == "your_openrouter_api_key_here":
self.send_json_response({"error": "Please set your OpenRouter API key in simple-server.py"}, 400)
return
# Make request to OpenRouter
if self.path == '/api/analyze':
response = self.analyze_tweet(data['tweet'])
else:
response = self.generate_reply(data['tweet'], data['preferences'])
self.send_json_response(response)
except Exception as e:
print(f"Error: {e}")
self.send_json_response({"error": str(e)}, 500)
def analyze_tweet(self, tweet):
messages = [
{
"role": "system",
"content": "You are an expert at analyzing social media content. Analyze tweets to understand their purpose, tone, context, and suggest appropriate response strategies."
},
{
"role": "user",
"content": f"""Analyze this tweet and provide insights about:
1. Main purpose/intent
2. Tone and sentiment
3. Key topics/themes
4. Suggested response approach
5. Any context clues
Tweet: "{tweet}" """
}
]
result = self.call_openrouter(messages, 300)
return {"analysis": result}
def generate_reply(self, tweet, preferences):
length_guide = {
"short": "1-2 sentences, concise and direct",
"medium": "2-3 sentences, balanced detail",
"long": "3-4 sentences, comprehensive response"
}
messages = [
{
"role": "system",
"content": "You are an expert at writing engaging Twitter replies. Create replies that are authentic, relevant, and match the requested style perfectly. Always stay respectful and constructive."
},
{
"role": "user",
"content": f"""Generate a Twitter reply to this tweet with these specifications:
Original Tweet: "{tweet}"
Reply Requirements:
- Length: {length_guide.get(preferences.get('length', 'medium'))}
- Writing Style: {preferences.get('style', 'casual')}
- Tone: {preferences.get('tone', 'neutral')}
- Include Emojis: {'Yes' if preferences.get('emoji', False) else 'No'}
Make the reply engaging, relevant, and natural. Don't mention that you're following specifications - just write a great reply."""
}
]
result = self.call_openrouter(messages, 280)
return {"reply": result}
def call_openrouter(self, messages, max_tokens):
url = "https://openrouter.ai/api/v1/chat/completions"
payload = {
"model": "meta-llama/llama-3.1-8b-instruct:free",
"messages": messages,
"max_tokens": max_tokens,
"temperature": 0.7
}
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"HTTP-Referer": "http://localhost:3000",
"X-Title": "Tweet Reply Generator"
}
req = urllib.request.Request(
url,
data=json.dumps(payload).encode('utf-8'),
headers=headers
)
with urllib.request.urlopen(req) as response:
result = json.loads(response.read().decode('utf-8'))
return result['choices'][0]['message']['content']
def send_json_response(self, data, status=200):
self.send_response(status)
self.send_header('Content-type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
self.end_headers()
self.wfile.write(json.dumps(data).encode('utf-8'))
def do_OPTIONS(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
self.end_headers()
if __name__ == "__main__":
print("🐦 Tweet Reply Generator - Python Server")
print("⚠️ This is a simple server for testing. Use Node.js server for production!")
print("")
if API_KEY == "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":
print("❌ Please edit simple-server.py and set your OpenRouter API key")
print(" Find the line: API_KEY = 'your_openrouter_api_key_here'")
print(" Replace with: API_KEY = 'your_actual_api_key'")
print("")
print("Get your free API key from: https://openrouter.ai/")
exit(1)
with socketserver.TCPServer(("", PORT), TweetReplyHandler) as httpd:
print(f"🚀 Server running on http://localhost:{PORT}")
print("📱 Open http://localhost:3000 in your browser")
print("⏹️ Press Ctrl+C to stop")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\n👋 Server stopped")