专栏名称: 奇舞精选
《奇舞精选》是由奇舞团维护的前端技术公众号。除周五外,每天向大家推荐一篇前端相关技术文章,每周五向大家推送汇总周刊内容。
目录
相关文章推荐
奇舞精选  ·  从 DeepSeek 看25年前端的一个小趋势 ·  20 小时前  
奇舞精选  ·  从 DeepSeek 看25年前端的一个小趋势 ·  20 小时前  
江苏新闻  ·  突发!DeepSeek暂停API服务充值 ·  昨天  
江苏新闻  ·  突发!DeepSeek暂停API服务充值 ·  昨天  
电商技术每天分享  ·  淘宝详情页服务器双图技术 ·  2 天前  
电商技术每天分享  ·  淘宝详情页服务器双图技术 ·  2 天前  
闽南日报  ·  突发!松下电器将解散 ·  2 天前  
51好读  ›  专栏  ›  奇舞精选

实战:基于 Next.js+MoonShot API 开发一个 Github Trending 总结助手

奇舞精选  · 公众号  · 科技自媒体  · 2024-10-29 17:50

主要观点总结

本文介绍了基于Next.js和MoonShot API开发一个GitHub Trending总结工具的过程,包括前端展示和后端数据抓取、翻译和API调用等关键技术实现细节。

关键观点总结

关键观点1: GitHub Trending 数据获取

使用Cheerio库从GitHub Trending页面抓取数据。

关键观点2: 使用MoonShot API翻译仓库描述(repo description)和readme。

调用MoonShot API进行自然语言翻译和总结。

关键观点3: 前端展示

使用Next.js和Tailwind CSS进行前端展示,利用Tailwind CSS的Typography插件优化排版。

关键观点4: 技术选型与实现

介绍项目的技术选型,包括前端框架Next.js、API服务GitHub API和MoonShot API的选择原因和使用方式。

关键观点5: 项目源码与参考链接

提供项目源码地址和相关参考链接,便于读者进一步学习和研究。


正文

本文作者为 360 奇舞团前端开发工程师

众所周知,《奇舞精选》目前有两个在运营的粉丝群,小编会不定期在群里分享一些关于 AI 或前端相关的最新资讯或开源项目,这些分享内容的一个来源就是 GitHub Trending:https://github.com/trending。为了提高阅读效率,小编开发了一个自动抓取 GitHub Trending 页面内容并通过大模型 Moonshot(月之暗面即 Kimi)翻译总结成中文的工具。本文详细介绍了小工具开发过程和遇到的问题及解决方案,最后附项目源码。

目标

  • 自动抓取 GitHub Trending 仓库列表。
  • 使用 MoonShot API 总结每个仓库的简介。
  • 展示一个用户友好的界面,列出描述和简介。

下面这个页面即最终的运行效果,小编还贴心的加上了暗黑模式。

功能需求:

  • 获取 GitHub Trending 数据。
  • 利用 OpenAI API 生成自然语言总结。

技术选型:

  • 前端框架 :Next.js、Tailwind CSS
  • API 服务 :GitHub API, MoonShot API

为什么选择 MoonShot API?因为 MoonShot API 对于新注册用户有一定的免费额度,且和 OpenAI 兼容,如果想迁移到 OpenAI 也非常方便。

技术实现

初始化 Next.js 项目

首先,我们使用以下命令创建一个 Next.js 项目:

npx create-next-app@latest
✔ What is your project named? … github-trending
✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias (@/*)? … No / Yes

初始化完项目并安装依赖后, yarn dev 启动项目。

获取 GitHub Trending 数据

由于 GitHub API 没有专门的 Trending API,我们需要通过 GitHub Trending 页面获取数据,可以使用 Puppeteer 或 Cheerio 进行页面抓取,这里我们选择 Cheerio。

Cheerio 是一个快速、灵活、轻量级的 JavaScript 库,专门用于在 Node.js 环境中操作和解析 HTML。它提供了一种类似于 jQuery 的 API,使得开发者可以方便地对 HTML 结构进行查询、修改等操作。

yarn add cheerio

抓取 GitHub Trending 的代码可以如下实现:

// app/page.js
import { load } from "cheerio";

const fetchTrendingRepos = async () => {
try {
const res = await fetch("https://github.com/trending?since=daily");
const htmlText = await res.text();
const $ = load(htmlText);
const repos = [];
const elements = $("h2.h3.lh-condensed");

for (const element of elements) {
// 从 html 里解析出 repoName
const repoName = $(element).find("a").attr("href").trim().substring(1);
console.log("repoName", repoName);
const repoDetail = await fetchRepoDetail(repoName);
if (!repoDetail) continue;

const translatedDescription = await translateDescription(
repoDetail.description || "无描述"
);

await delay(70 * 1000);

const summary = await summarizeReadme(repoName);

await delay(70 * 1000);

repos.push({
name: repoName,
desc: translatedDescription,
summary,
});
}

return repos;
} catch (error) {
console.error("Error fetching trending repositories:", error);
return [];
}
};

获取仓库详情

上面的代码解析出仓库名,接下来我们就可以调 GitHub API 来获取仓库详情了:

const fetchRepoDetail = async (repoName) => {
  try {
    const response = await fetch(`https://api.github.com/repos/${repoName}`);
    if (!response.ok) throw new Error("Failed to fetch repo details");
    return await response.json();
  } catch (error) {
    console.error(`Error fetching repo details for ${repoName}:`, error);
    return null;
  }
};

GitHub API 也有访问限制,对于未认证的请求:每小时的请求限额:60 次。对于认证的请求:每小时的请求限额:5000 次。

翻译 description 成中文

拿到详情,我们用大模型把 description 翻译成中文。因为 MoonShot 兼容 OpenAI SDK,因此我们先添加 OpenAI SDK 依赖。

yarn add openai

然后引入并添加配置:

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.MOONSHOT_API_KEY, //需要注册后申请
  baseURL"https://api.moonshot.cn/v1",
});

最后调用 chat 来进行翻译:


const translatedDescription = await translateDescription(
  repoDetail.description || "无描述"
);

const fetchMoonShotResponse = async (content, role) => {
  try {
    const completion = await client.chat.completions.create({
      model"moonshot-v1-8k",
      messages: [
        {
          role"system",
          content: role,
        },
        {
          role"user",
          content,
        },
      ],
      temperature0.3,
    });
    return completion.choices[0].message.content;
  } catch (error) {
    console .error("Error in request:", error);
    return "";
  }
};

const translateDescription = async (description) => {
  return await fetchMoonShotResponse(
    `${description} 翻译成中文`,
    "你是翻译专家,擅长各种语言翻译"
  );
};

总结 Readme


const summarizeReadme = async (repoName) => {
  try {
    const response = await fetch(
      `https://api.github.com/repos/${repoName}/readme`
    );
    if (!response.ok) throw new Error("Failed to fetch readme");

    const readmeData = await response.json();
    const readmeStr = atob(readmeData.content);

    return await fetchMoonShotResponse(
      `${readmeStr} 总结成200字的中文`,
      "你是翻译专家,擅长各种语言翻译和总结"
    );
  } catch (error) {
    console.error(`Error summarizing README for ${repoName}:`, error);
    return "";
  }
};

注意,对于免费用户 MoonShot 也有请求限制,因此,每次调用 MoonShot 后,需要增加 delay 避免频繁请求接口。参见:https://platform.moonshot.cn/docs/pricing/limits

用户等级 累计充值金额 并发 RPM TPM TPD
Free ¥ 0 1 3 32,000 1,500,000
Tier1 ¥ 50 50 200 128,000 10,000,000
Tier2 ¥ 100 100 500 128,000 20,000,000
Tier3 ¥ 500 200 5,000 384,000 Unlimited
Tier4 ¥ 5,000 400 5,000 768,000 Unlimited
Tier5 ¥ 20,000 1,000 10,000 2,000,000 Unlimited

以上我们就有了要展示在前端的所有数据:

  • repoName
  • description
  • summary

前端展示

前端展示我们使用 Tailwind CSS 官方插件 typography ,它简化了为文章、博客等长内容应用默认样式的过程,使文本更具可读性和美感。通过 prose 类来为内容块提供一组经过精心设计的排版样式。以下是详细用法和常见场景:

安装

首先,你需要在你的 Tailwind CSS 项目中安装 @tailwindcss/typography 插件:

yarn add @tailwindcss/typography

然后,在 tailwind.config.js 中引入该插件:

module.exports = {
  plugins: [
    require('@tailwindcss/typography'),   
  ],
}

基本用法

使用 prose 类可以让一整块内容的排版看起来更统一。例如:

<div class="prose">
  <h1






请到「今天看啥」查看全文


推荐文章
奇舞精选  ·  从 DeepSeek 看25年前端的一个小趋势
20 小时前
奇舞精选  ·  从 DeepSeek 看25年前端的一个小趋势
20 小时前
江苏新闻  ·  突发!DeepSeek暂停API服务充值
昨天
江苏新闻  ·  突发!DeepSeek暂停API服务充值
昨天
电商技术每天分享  ·  淘宝详情页服务器双图技术
2 天前
电商技术每天分享  ·  淘宝详情页服务器双图技术
2 天前
闽南日报  ·  突发!松下电器将解散
2 天前
历史震惊你  ·  《大悲咒》汉语版,太好听了!
7 年前