p / Client /comments.py
q6's picture
Endpoint
433e037
raw
history blame
3.45 kB
import os
import json
import requests
COMMENTS_LIMIT = 30
DEFAULT_ENDPOINT = "https://q6-p.hf.space"
def read_dotenv_value(path, key):
try:
with open(path, "r") as env_file:
for line in env_file:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
if k == key:
return v
except FileNotFoundError:
return None
return None
def get_phpsessid():
phpsessid = os.getenv("PHPSESSID")
if phpsessid:
return phpsessid
env_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".env"))
phpsessid = read_dotenv_value(env_path, "PHPSESSID")
if phpsessid:
return phpsessid
raise RuntimeError("PHPSESSID is not set in the environment or .env")
def get_endpoint():
endpoint = os.getenv("PIXIF_ENDPOINT")
if endpoint:
return endpoint.rstrip("/")
env_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".env"))
endpoint = read_dotenv_value(env_path, "PIXIF_ENDPOINT")
if endpoint:
return endpoint.rstrip("/")
return DEFAULT_ENDPOINT
def fetch_comments(post_ids, phpsessid, endpoint, limit=COMMENTS_LIMIT):
payload = {"post_ids": post_ids, "phpsessid": phpsessid, "limit": limit}
response = requests.post(f"{endpoint}/comments", json=payload, timeout=300)
response.raise_for_status()
data = response.json()
comments = data.get("comments", data)
if not isinstance(comments, dict):
raise RuntimeError("Unexpected response from comments endpoint.")
return comments
def parse_indexes(inputs):
indexes = []
for inp in inputs:
if "-" in inp:
start, end = map(int, inp.split("-"))
indexes.extend(range(start - 1, end))
elif inp.isdigit():
indexes.append(int(inp) - 1)
return indexes
def main():
os.chdir(os.path.dirname(os.path.abspath(__file__)))
os.makedirs("comments", exist_ok=True)
valid = [f for f in os.listdir() if f.endswith(".txt")]
for idx, file in enumerate(valid):
print(f"{idx + 1}: {file}")
if not valid:
print("No .txt files found in the Client directory.")
return
inputs = input("Enter the index of the file: ").split()
indexes = parse_indexes(inputs)
phpsessid = get_phpsessid()
endpoint = get_endpoint()
for index in indexes:
if index < 0 or index >= len(valid):
continue
group_name = valid[index].rsplit(".", 1)[0]
with open(valid[index], "r") as f:
raw_ids = f.read().split()
post_ids = [int(post_id) for post_id in raw_ids if post_id.isdigit()]
if not post_ids:
continue
try:
fetched = fetch_comments(post_ids, phpsessid, endpoint)
except Exception as exc:
print(f"Failed to fetch comments for {group_name}: {exc}")
fetched = {}
comments_by_post = {str(post_id): fetched.get(str(post_id), []) for post_id in post_ids}
output_path = os.path.join("comments", f"{group_name}.json")
with open(output_path, "w", encoding="utf-8") as f:
json.dump(comments_by_post, f, indent=2, ensure_ascii=False)
print(f"Saved comments to {output_path}")
if __name__ == "__main__":
main()