content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package de.fruiture.cor.ccs.git import de.fruiture.cor.ccs.cc.ConventionalCommitMessage import de.fruiture.cor.ccs.cc.ConventionalCommitMessage.Companion.message import de.fruiture.cor.ccs.cc.Description import de.fruiture.cor.ccs.cc.Type import io.kotest.matchers.shouldBe import kotlin.test.Test class GitCommitTest { @Test fun `parse conventional commit`() { val commit = GitCommit( hash = "cafe", date = ZonedDateTime("2001-01-01T12:00:00Z"), message = "feat: a feature" ) commit.conventional shouldBe message("feat: a feature") commit.type shouldBe Type("feat") commit.hasBreakingChange shouldBe false } @Test fun `tolerate invalid commit message`() { val commit = GitCommit( hash = "cafe", date = ZonedDateTime("2001-01-01T12:00:00Z"), message = "non-conventional commit" ) commit.conventional shouldBe ConventionalCommitMessage( type = NON_CONVENTIONAL_COMMIT_TYPE, description = Description("non-conventional commit") ) commit.type shouldBe Type("none") commit.hasBreakingChange shouldBe false } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/git/GitCommitTest.kt
1913711391
package de.fruiture.cor.ccs.git import de.fruiture.cor.ccs.git.VersionTag.Companion.versionTag import de.fruiture.cor.ccs.semver.Version.Companion.version import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import kotlin.test.Test class GitTest { private val forEachRef = listOf( "for-each-ref", "--merged", "HEAD", "--sort=-committerdate", "--format=%(refname:short)", "refs/tags/*.*.*" ) @Test fun `get latest version or release tag using git for-each-ref`() { val sys = mockk<SystemCaller>().apply { every { call("git", forEachRef) } returns SystemCallResult( code = 0, stdout = listOf( "v2.1.0-SNAPSHOT.1", "2.1.0-SNAPSHOT.2", "rel2.0.0", "1.3.9", "1.3.9-RC.7" ) ) } val git = Git(sys) git.getLatestVersionTag() shouldBe versionTag("2.1.0-SNAPSHOT.2") git.getLatestVersionTag(before(version("2.1.0-SNAPSHOT.2"))) shouldBe versionTag("v2.1.0-SNAPSHOT.1") git.getLatestVersionTag(before(version("2.1.0-SNAPSHOT.1"))) shouldBe versionTag("rel2.0.0") git.getLatestReleaseTag() shouldBe versionTag("rel2.0.0") git.getLatestReleaseTag(before(version("2.1.0-SNAPSHOT.2"))) shouldBe versionTag("rel2.0.0") git.getLatestReleaseTag(before(version("2.0.0"))) shouldBe versionTag("1.3.9") git.getLatestReleaseTag(before(version("1.3.9"))) shouldBe null git.getLatestVersionTag(before(version("1.3.9"))) shouldBe versionTag("1.3.9-RC.7") git.getLatestVersionTag(before(version("1.3.9-RC.7"))) shouldBe null } @Test fun `find no version`() { val sys = mockk<SystemCaller>().apply { every { call("git", forEachRef) } returns SystemCallResult( code = 0, stdout = emptyList() ) } Git(sys).getLatestReleaseTag() shouldBe null Git(sys).getLatestVersionTag() shouldBe null } @Test fun `tolerate non-versions`() { val sys = mockk<SystemCaller>().apply { every { call("git", forEachRef) } returns SystemCallResult( code = 0, stdout = listOf( "2.1.0-SNAPSHOT.1", "2.1.0-SNAPSHOT.2", "accidental.version.string", "2.0.0" ) ) } Git(sys).getLatestReleaseTag() shouldBe versionTag("2.0.0") } @Test fun `any error`() { val sys = object : SystemCaller { override fun call(command: String, arguments: List<String>): SystemCallResult { return SystemCallResult( code = 127, stderr = listOf("command not found: $command") ) } } shouldThrow<RuntimeException> { Git(sys).getLatestVersionTag() } } @Test fun `get machine readable log`() { val sys = object : SystemCaller { override fun call(command: String, arguments: List<String>): SystemCallResult { command shouldBe "git" arguments shouldBe listOf("log", "--format=format:%H %aI%n%B%n%x1E", "1.0.0..HEAD") return SystemCallResult( code = 0, stdout = """ 948f00f8b349c6f9652809f924254ffe7a497227 2024-01-20T21:51:33+01:00 feat: blablabla BREAKING CHANGE: did something dudu here ${RECORD_SEPARATOR} b8d181d9e803da9ceba0c3c4918317124d678656 2024-01-20T21:31:01+01:00 non conventional commit """.trimIndent().lines() ) } } Git(sys).getLogX( from = TagName("1.0.0") ) shouldBe listOf( GitCommit( hash = "948f00f8b349c6f9652809f924254ffe7a497227", date = ZonedDateTime("2024-01-20T21:51:33+01:00"), message = """ feat: blablabla BREAKING CHANGE: did something dudu here """.trimIndent() ), GitCommit( hash = "b8d181d9e803da9ceba0c3c4918317124d678656", date = ZonedDateTime("2024-01-20T21:31:01+01:00"), message = "non conventional commit" ) ) } @Test fun `get full log`() { val sys = object : SystemCaller { override fun call(command: String, arguments: List<String>): SystemCallResult { command shouldBe "git" arguments shouldBe listOf("log", "--format=format:%H %aI%n%B%n%x1E", "HEAD") return SystemCallResult( code = 0, stdout = """ b8d181d9e803da9ceba0c3c4918317124d678656 2024-01-20T21:31:01+01:00 non conventional commit """.trimIndent().lines() ) } } Git(sys).getLogX() shouldBe listOf( GitCommit( hash = "b8d181d9e803da9ceba0c3c4918317124d678656", date = ZonedDateTime("2024-01-20T21:31:01+01:00"), message = "non conventional commit" ) ) } @Test fun `get log until a version`() { val sys = mockk<SystemCaller>().apply { every { call( "git", listOf( "log", "--format=format:%H %aI%n%B%n%x1E", "v1.0.0" ) ) } returns SystemCallResult( 0, stdout = """ b8d181d9e803da9ceba0c3c4918317124d678656 2024-01-20T21:31:01+01:00 first commit """.trimIndent().lines() ) } Git(sys).getLogX(to = TagName("v1.0.0")) shouldHaveSize 1 } }
git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/git/GitTest.kt
543333548
import de.fruiture.cor.ccs.CCSApplication import de.fruiture.cor.ccs.CLI import de.fruiture.cor.ccs.git.Git import de.fruiture.cor.ccs.git.KommandSystemCaller fun main(args: Array<String>) { CLI(CCSApplication(Git(KommandSystemCaller()))).main(args) }
git-ccs/src/commonMain/kotlin/main.kt
4031198852
// this entire file is overridden in CI, don't put anything else but the following line here: const val VERSION = "0.0.1-DEV.SNAPSHOT"
git-ccs/src/commonMain/kotlin/version.kt
2675147533
package de.fruiture.cor.ccs import VERSION import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.NoOpCliktCommand import com.github.ajalt.clikt.core.ProgramResult import com.github.ajalt.clikt.core.subcommands import com.github.ajalt.clikt.parameters.groups.* import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parameters.types.int import de.fruiture.cor.ccs.cc.Type import de.fruiture.cor.ccs.semver.ChangeType import de.fruiture.cor.ccs.semver.PreReleaseIndicator import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.static import de.fruiture.cor.ccs.semver.Version.Companion.version private class MappingOptions : OptionGroup( name = "Version Bumping Options", help = "adjust which conventional commit types have which semantic version effect\n\n" + " - each option takes a list (comma-separated) of commit types,\n" + " - 'default' will match all other commit types,\n" + " - 'none' will match commits that are not valid conventional commits" ) { val noChangeTypes by option( "-n", "--none", help = "commit types that should trigger no version change, empty by default" ).convert { Type(it) }.split(",").default(emptyList()) val patchTypes by option( "-p", "--patch", help = "commit types that should trigger a patch level change, default: 'default', i.e." + "usually all commits trigger at least a patch level change" ).convert { Type(it) }.split(",").default(emptyList()) val minorTypes by option( "-m", "--minor", help = "commit types that should trigger a minor level change, by default: 'feat'" ).convert { Type(it) }.split(",").default(emptyList()) val majorTypes by option( "-M", "--major", help = "commit types that should trigger a major level change, empty by default" ).convert { Type(it) }.split(",").default(emptyList()) fun getMapping() = ChangeMapping() .add(ChangeType.NONE, noChangeTypes) .add(ChangeType.PATCH, patchTypes) .add(ChangeType.MINOR, minorTypes) .add(ChangeType.MAJOR, majorTypes) } private class LogOptions : OptionGroup() { val release by option( "-r", "--release", help = "only consider releases (ignore pre-releases)" ).flag() val target by option( "-t", "--target", help = "look for latest version before a given version (instead of HEAD)" ).convert { version(it) } } class CLI(app: CCSApplication) : NoOpCliktCommand( name = "git-ccs", help = "Conventional Commits & Semantic Versioning Utility for Git Repositories" ) { init { versionOption(VERSION) subcommands(object : NoOpCliktCommand( name = "next", help = "compute the next semantic version based on changes since the last version tag", ) { init { subcommands( object : CliktCommand( name = "release", help = "create a release version, e.g. 1.2.3" ) { val mappingOptions by MappingOptions() override fun run() { echo( app.getNextRelease(mappingOptions.getMapping()), trailingNewline = false ) } }, object : CliktCommand( name = "pre-release", help = "create a pre-release version, e.g. 1.2.3-RC.1" ) { val strategy by mutuallyExclusiveOptions( option( "-c", "--counter", help = "(default) add a numeric release candidate counter, e.g. 1.2.3-RC.3" ).flag().convert { counter() }, option( "-s", "--static", help = "just append a fixed pre-release identifier 'SNAPSHOT' (maven convention), e.g. 1.2.3-SNAPSHOT" ).flag().convert { static() }, option( "-f", "--format", help = "specify a pattern, like: RC.1.DEV, where 'RC.1' would become a counter and 'DEV' would be static" ).convert { PreReleaseIndicator.Strategy.deduct(it) } ).single().default(counter()) val mappingOptions by MappingOptions() override fun run() { echo( message = app.getNextPreRelease( strategy = strategy, changeMapping = mappingOptions.getMapping() ), trailingNewline = false ) } }) } }, object : CliktCommand( name = "log", help = "get commit log since last version as machine-friendly JSON representation" ) { val logOptions by LogOptions() override fun run() { echo( app.getChangeLogJson(release = logOptions.release, before = logOptions.target), trailingNewline = false ) } }, object : CliktCommand( name = "latest", help = "find the latest version (release or pre-release)" ) { val logOptions by LogOptions() override fun run() { val latestVersion = app.getLatestVersion(release = logOptions.release, before = logOptions.target) if (latestVersion != null) { echo(latestVersion, trailingNewline = false) } else { echo("no version found", err = true) throw ProgramResult(1) } } }, object : CliktCommand( name = "changes", help = "summarize changes (see `log`) as markdown document (changelog)" ) { val logOptions by LogOptions() val sections by option( "-s", "--section", help = "specify section headlines and their types, types can be comma-separated'\n\n" + "e.g. (default) -s 'Features=feat' -s 'Bugfixes=fix'" ).splitPair().convert { (hl, types) -> hl to types.split(',').map { Type(it) }.toSet() }.multiple().toMap() val breakingChanges by option( "-b", "--breaking-changes", help = "adjust the headline for the breaking changes section (default 'Breaking Changes')" ).default("Breaking Changes") val level by option( "-l", "--level", help = "level of headlines in markdown, default is 2: ## Headline" ).int().default(2).check(message = "must be in 1 .. 7") { it in 1..7 } override fun run() { val config = if (sections.isEmpty()) Sections.default() else Sections(sections) echo( app.getChangeLogMarkdown( release = logOptions.release, target = logOptions.target, sections = config.setBreakingChanges(breakingChanges), level = level ), trailingNewline = false ) } }) } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/CLI.kt
337591374
package de.fruiture.cor.ccs import de.fruiture.cor.ccs.cc.Type import de.fruiture.cor.ccs.git.GitCommit import de.fruiture.cor.ccs.semver.ChangeType val DEFAULT_COMMIT_TYPE = Type("default") val FEATURE_COMMIT_TYPE = Type("feat") val FIX_COMMIT_TYPE = Type("fix") data class ChangeMapping( private val types: Map<Type, ChangeType> = mapOf( FEATURE_COMMIT_TYPE to ChangeType.MINOR, FIX_COMMIT_TYPE to ChangeType.PATCH, DEFAULT_COMMIT_TYPE to ChangeType.PATCH ) ) { private val defaultChange = types[DEFAULT_COMMIT_TYPE]!! fun of(history: List<GitCommit>): ChangeType = history.maxOfOrNull(::of) ?: defaultChange fun of(commit: GitCommit) = if (commit.hasBreakingChange) ChangeType.MAJOR else of(commit.type) fun of(type: Type) = types.getOrElse(type) { defaultChange } operator fun plus(type: Pair<Type, ChangeType>) = copy(types = types + type) fun add(changeType: ChangeType, types: List<Type>) = copy(types = this.types + types.associateWith { changeType }) }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/ChangeMapping.kt
171597580
package de.fruiture.cor.ccs import de.fruiture.cor.ccs.cc.Type data class Sections( val config: Map<String, Set<Type>> = emptyMap(), val breakingChanges: String = "Breaking Changes" ) { interface TypeFilter { operator fun contains(type: Type): Boolean } companion object { fun default() = Sections( mapOf( "Features" to setOf(FEATURE_COMMIT_TYPE), "Bugfixes" to setOf(FIX_COMMIT_TYPE), "Other" to setOf(DEFAULT_COMMIT_TYPE), ) ) } private val allAssignedTypes = config.values.flatten().toSet() fun toFilter(set: Set<Type>): TypeFilter { val matchesDefault = set.contains(DEFAULT_COMMIT_TYPE) return object : TypeFilter { override fun contains(type: Type): Boolean { if (matchesDefault) { if (type !in allAssignedTypes) return true } return set.contains(type) } } } operator fun plus(mappings: Map<String, Set<Type>>): Sections { return copy(config = config + mappings) } inline fun forEach(function: (String, TypeFilter) -> Unit) { config.forEach { function(it.key, toFilter(it.value.toSet())) } } fun setBreakingChanges(headline: String) = copy(breakingChanges = headline) }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/Sections.kt
1113246759
package de.fruiture.cor.ccs.semver import de.fruiture.cor.ccs.semver.Build.Companion.add import de.fruiture.cor.ccs.semver.Build.Companion.suffix import de.fruiture.cor.ccs.semver.NumericIdentifier.Companion.numeric import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter enum class ChangeType { NONE, PATCH, MINOR, MAJOR } private fun Int.then(compare: () -> Int) = if (this == 0) compare() else this internal data class VersionCore( val major: NumericIdentifier, val minor: NumericIdentifier, val patch: NumericIdentifier ) : Comparable<VersionCore> { init { require((major.zero && minor.zero && patch.zero).not()) } companion object { fun of(major: Int, minor: Int, patch: Int) = VersionCore( NumericIdentifier(major), NumericIdentifier(minor), NumericIdentifier(patch) ) fun parse(string: String): VersionCore { val (ma, mi, pa) = string.split('.') return of(ma.toInt(), mi.toInt(), pa.toInt()) } } override fun compareTo(other: VersionCore) = major.compareTo(other.major) .then { minor.compareTo(other.minor) } .then { patch.compareTo(other.patch) } override fun toString() = "$major.$minor.$patch" fun bump(type: ChangeType) = when (type) { ChangeType.NONE -> this ChangeType.PATCH -> copy(patch = patch + 1) ChangeType.MINOR -> copy(minor = minor + 1, patch = 0.numeric) ChangeType.MAJOR -> copy(major = major + 1, minor = 0.numeric, patch = 0.numeric) } val type: ChangeType by lazy { if (patch.nonZero) ChangeType.PATCH else if (minor.nonZero) ChangeType.MINOR else if (major.nonZero) ChangeType.MAJOR else throw IllegalStateException("v0.0.0 is not defined") } } private val searchRegexp = Regex("\\d+\\.\\d+\\.\\d+(?:[-+.\\w]+)?") sealed class Version : Comparable<Version> { abstract val release: Release abstract val build: Build? internal abstract val core: VersionCore val type get() = core.type abstract fun build(suffix: String): Version abstract operator fun plus(preRelease: PreReleaseIndicator): PreRelease abstract operator fun plus(build: Build): Version abstract fun next(type: ChangeType): Release internal abstract fun nextPreRelease(strategy: PreReleaseIndicator.Strategy = counter()): PreRelease abstract fun nextPreRelease(type: ChangeType, strategy: PreReleaseIndicator.Strategy = counter()): PreRelease companion object { val initial = Release(VersionCore.of(0, 0, 1)) val stable = Release(VersionCore.of(1, 0, 0)) fun version(string: String): Version { val (prefix, build) = string.indexOf('+').let { if (it == -1) string to null else { val prefix = string.substring(0, it) val buildSuffix = string.substring(it + 1) val build = Build.build(buildSuffix) prefix to build } } val hyphen = prefix.indexOf('-') return if (hyphen == -1) Release(VersionCore.parse(prefix), build) else { PreRelease( VersionCore.parse(prefix.substring(0, hyphen)), PreReleaseIndicator.preRelease(prefix.substring(hyphen + 1)), build ) } } fun extractVersion(string: String) = searchRegexp.find(string)?.let { match -> runCatching { version(match.value) }.getOrNull() } } } data class PreRelease internal constructor( override val core: VersionCore, val pre: PreReleaseIndicator, override val build: Build? = null ) : Version() { override val release = Release(core) override fun compareTo(other: Version): Int { return when (other) { is PreRelease -> core.compareTo(other.core) .then { pre.compareTo(other.pre) } is Release -> core.compareTo(other.core).then { -1 } } } override fun toString() = "$core-$pre${build.suffix}" override fun build(suffix: String) = copy(build = Build.build(suffix)) override fun plus(preRelease: PreReleaseIndicator) = copy(pre = pre + preRelease) override fun plus(build: Build) = copy(build = this.build add build) override fun nextPreRelease(strategy: PreReleaseIndicator.Strategy) = copy(pre = strategy.next(pre), build = null) override fun next(type: ChangeType): Release { val changeToHere = release.type return if (changeToHere >= type) release else release.next(type) } override fun nextPreRelease(type: ChangeType, strategy: PreReleaseIndicator.Strategy): PreRelease { val changeToHere = release.type return if (changeToHere >= type) nextPreRelease(strategy) else release.next(type).nextPreRelease(strategy) } } data class Release internal constructor(override val core: VersionCore, override val build: Build? = null) : Version() { override val release = this override fun compareTo(other: Version): Int { return when (other) { is PreRelease -> -other.compareTo(this) is Release -> core.compareTo(other.core) } } override fun toString() = "$core${build.suffix}" fun preRelease(suffix: String) = plus(PreReleaseIndicator.preRelease(suffix)) override fun build(suffix: String) = copy(build = Build.build(suffix)) override fun plus(preRelease: PreReleaseIndicator) = PreRelease(core, preRelease, build) override fun plus(build: Build) = copy(build = this.build add build) override fun next(type: ChangeType) = Release(core.bump(type)) override fun nextPreRelease(strategy: PreReleaseIndicator.Strategy) = PreRelease(core, strategy.start()) override fun nextPreRelease(type: ChangeType, strategy: PreReleaseIndicator.Strategy) = next(type).nextPreRelease(strategy) }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/semver/Version.kt
3353056321
package de.fruiture.cor.ccs.semver import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric import de.fruiture.cor.ccs.semver.NumericIdentifier.Companion.numeric import de.fruiture.cor.ccs.semver.PreReleaseIdentifier.Companion.identifier sealed class PreReleaseIdentifier : Comparable<PreReleaseIdentifier> { data class AlphaNumeric(val identifier: AlphaNumericIdentifier) : PreReleaseIdentifier() { override fun compareTo(other: PreReleaseIdentifier) = when (other) { is AlphaNumeric -> identifier.compareTo(other.identifier) is Numeric -> 1 } override fun toString() = identifier.toString() } data class Numeric(val identifier: NumericIdentifier) : PreReleaseIdentifier() { override fun compareTo(other: PreReleaseIdentifier) = when (other) { is Numeric -> identifier.compareTo(other.identifier) is AlphaNumeric -> -1 } override fun toString() = identifier.toString() fun bump() = Numeric(identifier + 1) } companion object { fun identifier(identifier: AlphaNumericIdentifier) = AlphaNumeric(identifier) fun identifier(identifier: NumericIdentifier) = Numeric(identifier) fun identifier(string: String) = if (string.all { it.digit }) identifier(NumericIdentifier(string.toInt())) else identifier(AlphaNumericIdentifier(string)) } } data class PreReleaseIndicator(val identifiers: List<PreReleaseIdentifier>) : Comparable<PreReleaseIndicator> { init { require(identifiers.isNotEmpty()) { "at least one identifier required" } } override fun compareTo(other: PreReleaseIndicator): Int { return identifiers.asSequence().zip(other.identifiers.asSequence()) { a, b -> a.compareTo(b) }.firstOrNull { it != 0 } ?: identifiers.size.compareTo(other.identifiers.size) } override fun toString() = identifiers.joinToString(".") operator fun plus(other: PreReleaseIndicator) = PreReleaseIndicator(this.identifiers + other.identifiers) companion object { fun of(vararg identifiers: PreReleaseIdentifier) = PreReleaseIndicator(listOf(*identifiers)) fun preRelease(string: String): PreReleaseIndicator = PreReleaseIndicator(string.split('.').map { identifier(it) }) } interface Strategy { fun next(indicator: PreReleaseIndicator): PreReleaseIndicator fun start(): PreReleaseIndicator companion object { val DEFAULT_STATIC = "SNAPSHOT".alphanumeric val DEFAULT_COUNTER = "RC".alphanumeric fun counter(identifier: AlphaNumericIdentifier = DEFAULT_COUNTER): Strategy = CounterStrategy(identifier) private data class CounterStrategy(val identifier: AlphaNumericIdentifier) : Strategy { override fun next(indicator: PreReleaseIndicator) = indicator.bumpCounter(identifier(identifier)) override fun start() = of(identifier(identifier), identifier(1.numeric)) } private fun PreReleaseIndicator.bumpCounter(identifier: PreReleaseIdentifier): PreReleaseIndicator { val replaced = sequence { var i = 0 var found = false while (i < identifiers.size) { val k = identifiers[i] if (k == identifier) { found = true if (i + 1 < identifiers.size) { val v = identifiers[i + 1] if (v is PreReleaseIdentifier.Numeric) { yield(k) yield(v.bump()) i += 2 continue } } yield(k) yield(PreReleaseIdentifier.Numeric(2.numeric)) i += 1 continue } yield(k) i += 1 continue } if (!found) { yield(identifier) yield(identifier(1.numeric)) } }.toList() return copy(identifiers = replaced) } fun static(identifier: AlphaNumericIdentifier = DEFAULT_STATIC): Strategy = Static(identifier) private data class Static(val identifier: AlphaNumericIdentifier) : Strategy { override fun next(indicator: PreReleaseIndicator) = identifier(identifier).let { if (it in indicator.identifiers) indicator else indicator + of(it) } override fun start() = of(identifier(identifier)) } operator fun Strategy.plus(then: Strategy): Strategy = Combined(this, then) fun deduct(spec: String): Strategy { val identifiers = preRelease(spec).identifiers return sequence { var i = 0 while (i < identifiers.size) { val k = identifiers[i] if (k is PreReleaseIdentifier.AlphaNumeric) { if (i + 1 < identifiers.size) { val v = identifiers[i + 1] if (v is PreReleaseIdentifier.Numeric) { this.yield(counter(k.identifier)) i += 2 continue } } this.yield(static(k.identifier)) } i++ } }.reduce { a, b -> a + b } } private data class Combined(val first: Strategy, val second: Strategy) : Strategy { override fun next(indicator: PreReleaseIndicator): PreReleaseIndicator { return indicator.let(first::next).let(second::next) } override fun start(): PreReleaseIndicator { return first.start().let(second::next) } } } } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/semver/PreReleaseIndicator.kt
2464811486
package de.fruiture.cor.ccs.semver sealed class BuildIdentifier { data class AlphaNumeric(val identifier: AlphaNumericIdentifier) : BuildIdentifier() { override fun toString() = identifier.toString() } data class Digits(val digits: DigitIdentifier) : BuildIdentifier() { override fun toString() = digits.toString() } companion object { fun identifier(identifier: AlphaNumericIdentifier) = AlphaNumeric(identifier) fun identifier(digits: DigitIdentifier) = Digits(digits) fun identifier(string: String) = if (string.all { it.digit }) identifier(DigitIdentifier(string)) else identifier(AlphaNumericIdentifier(string)) } } data class Build(val identifiers: List<BuildIdentifier>) { init { require(identifiers.isNotEmpty()) } override fun toString() = identifiers.joinToString(".") operator fun plus(build: Build): Build = Build(identifiers + build.identifiers) companion object { fun build(suffix: String) = Build(suffix.split('.').map(BuildIdentifier.Companion::identifier)) val Build?.suffix get() = this?.let { "+$it" } ?: "" infix fun Build?.add(build: Build) = this?.let { it + build } ?: build } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/semver/Build.kt
3429490097
package de.fruiture.cor.ccs.semver import kotlin.jvm.JvmInline private const val LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" private const val NON_DIGITS = "-$LETTERS" private const val POSITIVE_DIGITS = "123456789" private const val DIGITS = "0$POSITIVE_DIGITS" private const val IDENTIFIER_CHARACTERS = "$NON_DIGITS$DIGITS" internal val Char.digit get() = this in DIGITS internal val Char.nonDigit get() = this in NON_DIGITS internal val Char.identifier get() = this in IDENTIFIER_CHARACTERS @JvmInline value class AlphaNumericIdentifier(private val value: String) : Comparable<AlphaNumericIdentifier> { init { require(value.isNotEmpty()) { "identifier cannot be empty" } require(value.all { it.identifier }) { "identifier '$value' must only contain: $IDENTIFIER_CHARACTERS" } require(value.any { it.nonDigit }) { "identifier '$value' must contain at leas one non-digit" } } override fun compareTo(other: AlphaNumericIdentifier) = value.compareTo(other.value) override fun toString() = value companion object { val String.alphanumeric get() = AlphaNumericIdentifier(this) } } @JvmInline value class NumericIdentifier(private val value: Int) : Comparable<NumericIdentifier> { init { require(value >= 0) { "numeric identifier must be positive integer" } } override fun compareTo(other: NumericIdentifier) = value.compareTo(other.value) override fun toString() = value.toString() operator fun plus(i: Int): NumericIdentifier { require(i >= 0) return NumericIdentifier(value + i) } val zero get() = value == 0 val nonZero get() = !zero companion object { val Int.numeric get() = NumericIdentifier(this) } } @JvmInline value class DigitIdentifier(private val value: String) { init { require(value.isNotEmpty()) { "identifier cannot be empty" } require(value.all { it.digit }) { "identifier '$value' must only contain digits" } } override fun toString() = value companion object { val String.digits get() = DigitIdentifier(this) } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/semver/Identifiers.kt
2120321050
package de.fruiture.cor.ccs import de.fruiture.cor.ccs.git.* import de.fruiture.cor.ccs.semver.PreRelease import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy import de.fruiture.cor.ccs.semver.Release import de.fruiture.cor.ccs.semver.Version import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json class CCSApplication( private val git: Git ) { private fun getChangeType(latestVersion: VersionTag, mapping: ChangeMapping) = mapping.of(git.getLogX(latestVersion.tag)) fun getNextRelease(changeMapping: ChangeMapping = ChangeMapping()): Release { val latestVersion = git.getLatestVersionTag() ?: return Version.initial val changeType = getChangeType(latestVersion, changeMapping) return latestVersion.version.next(changeType) } fun getNextPreRelease(strategy: Strategy, changeMapping: ChangeMapping = ChangeMapping()): PreRelease { val latestVersion = git.getLatestVersionTag() ?: return initialPreRelease(strategy) val changeType = getChangeType(latestVersion, changeMapping) return latestVersion.version.nextPreRelease(changeType, strategy) } private fun initialPreRelease(strategy: Strategy) = Version.initial + strategy.start() @OptIn(ExperimentalSerializationApi::class) private val json = Json { explicitNulls = false } fun getChangeLogJson(release: Boolean = false, before: Version? = null): String { val commits = getChanges(release, before) return json.encodeToString(commits) } private fun getChanges(release: Boolean, before: Version? = null): List<GitCommit> { val from = getLatest(release, optionalFilterBefore(before)) val to = if (before == null) null else getLatest(false, until(before)) return git.getLogX(from = from?.tag, to = to?.tag) } fun getLatestVersion(release: Boolean = false, before: Version? = null): String? = getLatest(release, optionalFilterBefore(before))?.version?.toString() private fun optionalFilterBefore(before: Version?) = if (before == null) any else before(before) private fun getLatest(release: Boolean, filter: VersionFilter): VersionTag? { return if (release) git.getLatestReleaseTag(filter) else git.getLatestVersionTag(filter) } fun getChangeLogMarkdown( release: Boolean = false, target: Version? = null, sections: Sections = Sections.default(), level: Int = 2 ) = sequence { val hl = "#".repeat(level) val commits = getChanges(release, target).map { it.conventional } val breakingChanges = commits.mapNotNull { it.breakingChange } if (breakingChanges.isNotEmpty()) { yield("$hl ${sections.breakingChanges}\n") breakingChanges.forEach { yield("* $it") } yield("") } sections.forEach { headline, types -> val selectedCommits = commits.filter { it.type in types } if (selectedCommits.isNotEmpty()) { yield("$hl $headline\n") selectedCommits.forEach { yield("* ${it.description}") } yield("") } } }.joinToString("\n") }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/CCSApplication.kt
922663514
package de.fruiture.cor.ccs.cc import de.fruiture.cor.ccs.cc.Scope.Companion.suffix import kotlinx.serialization.* import kotlinx.serialization.builtins.MapSerializer import kotlinx.serialization.builtins.serializer import kotlinx.serialization.descriptors.mapSerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlin.jvm.JvmInline @JvmInline @Serializable value class Type(private val value: String) { init { require(value.isNotBlank()) } override fun toString() = value } @JvmInline @Serializable value class Description(val value: String) { init { require(value.isNotBlank()) } override fun toString() = value } @JvmInline @Serializable value class Body(private val value: String) { constructor(paragraphs: List<String>) : this(paragraphs.joinToString("\n\n")) init { require(value.isNotBlank()) } override fun toString() = value } sealed class Footer { abstract val key: String abstract val value: String override fun toString() = "$key: $value" } data class GenericFooter(override val key: String, override val value: String) : Footer() { init { require(key.none { it.isWhitespace() }) require(value.isNotBlank()) } override fun toString() = super.toString() } private val VALID_KEYS = listOf("BREAKING CHANGE", "BREAKING-CHANGE") private val DEFAULT_KEY = VALID_KEYS.first() @Serializable data class BreakingChange(override val key: String, override val value: String) : Footer() { constructor(value: String) : this(DEFAULT_KEY, value) init { require(key in VALID_KEYS) require(value.isNotBlank()) } override fun toString() = super.toString() } @JvmInline @Serializable value class Scope(private val value: String) { init { require(value.isNotBlank()) } override fun toString() = value companion object { val Scope?.suffix get() = if (this == null) "" else "($this)" } } @OptIn(ExperimentalSerializationApi::class) @Serializable data class ConventionalCommitMessage( val type: Type, val description: Description, val scope: Scope? = null, val body: Body? = null, val footers: @Serializable(with = FootersSerializer::class) List<@Contextual Footer> = emptyList(), val headlineBreakingChange: Boolean = false ) { private val exclamation: String get() = if (headlineBreakingChange) "!" else "" private val effectiveBreakingChange: BreakingChange? = if (headlineBreakingChange) BreakingChange(description.value) else footers.filterIsInstance<BreakingChange>().firstOrNull() @EncodeDefault val breakingChange = effectiveBreakingChange?.value val hasBreakingChange: Boolean = breakingChange != null companion object { fun message(text: String): ConventionalCommitMessage { val paragraphs = text.split(Regex("\\n\\n")).map(String::trim).filter(String::isNotEmpty) val headline = headline(paragraphs.first()) val tail = paragraphs.drop(1) return if (tail.isNotEmpty()) { val footers = footers(tail.last()) if (footers.isNotEmpty()) { val body = tail.dropLast(1) if (body.isNotEmpty()) headline + Body(body) + footers else headline + footers } else { headline + Body(tail) } } else { headline } } private fun headline(headline: String): ConventionalCommitMessage { return Regex("(\\w+)(?:\\((\\w+)\\))?(!)?: (.+)") .matchEntire(headline)?.destructured?.let { (type, scope, excl, description) -> return ConventionalCommitMessage( type = Type(type), description = Description(description), scope = if (scope.isNotEmpty()) Scope(scope) else null, headlineBreakingChange = excl.isNotEmpty() ) } ?: throw IllegalArgumentException("no valid headline: '$headline‘") } private fun footers(paragraph: String) = Regex("^([\\S-]+|BREAKING CHANGE): (.+?)$", RegexOption.MULTILINE).findAll(paragraph) .map { it.destructured } .map { (k, v) -> footer(k, v) } .toList() private fun footer(k: String, v: String) = if (k == "BREAKING CHANGE" || k == "BREAKING-CHANGE") BreakingChange(k, v) else GenericFooter(k, v) object FootersSerializer : KSerializer<List<Footer>> { override val descriptor = mapSerialDescriptor<String, String>() private val mapSerializer = MapSerializer(String.serializer(), String.serializer()) override fun deserialize(decoder: Decoder): List<Footer> { return decoder.decodeSerializableValue(mapSerializer) .map { (k, v) -> footer(k, v) } } override fun serialize(encoder: Encoder, value: List<Footer>) { return encoder.encodeSerializableValue(mapSerializer, value.associate { it.key to it.value }) } } } private operator fun plus(footers: List<Footer>) = copy(footers = this.footers + footers) private operator fun plus(body: Body) = copy(body = body) override fun toString(): String { val out = StringBuilder() out.append(headline()) body?.let { out.appendLine() out.appendLine() out.append(it) } if (footers.isNotEmpty()) { out.appendLine() out.appendLine() out.append(footers.joinToString("\n")) } return out.toString() } private fun headline() = "$type${scope.suffix}$exclamation: $description" }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/cc/ConventionalCommitMessage.kt
302653052
package de.fruiture.cor.ccs.git import com.kgit2.kommand.process.Command import com.kgit2.kommand.process.Stdio class KommandSystemCaller : SystemCaller { override fun call(command: String, arguments: List<String>): SystemCallResult { val child = Command(command) .args(arguments) .stdout(Stdio.Pipe) .stderr(Stdio.Pipe) .spawn() val code = child.wait() return SystemCallResult( code = code, stdout = child.bufferedStdout()?.lines()?.toList() ?: emptyList(), stderr = child.bufferedStderr()?.lines()?.toList() ?: emptyList() ) } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/git/KommandSystemCaller.kt
355279750
package de.fruiture.cor.ccs.git import de.fruiture.cor.ccs.semver.Release import de.fruiture.cor.ccs.semver.Version import kotlin.jvm.JvmInline const val RECORD_SEPARATOR = '\u001e' typealias VersionFilter = (Version) -> Boolean val any: VersionFilter = { true } @JvmInline private value class BeforeFilter(val maxExclusive: Version) : VersionFilter { override fun invoke(it: Version) = it < maxExclusive } fun before(maxExclusive: Version): VersionFilter = BeforeFilter(maxExclusive) @JvmInline private value class UntilFilter(val maxInclusive: Version) : VersionFilter { override fun invoke(it: Version) = it <= maxInclusive } fun until(maxInclusive: Version): VersionFilter = UntilFilter(maxInclusive) class Git(private val sys: SystemCaller) { fun getLatestVersionTag(filter: VersionFilter = any): VersionTag? { return getAllVersionTags(filter).maxOrNull() } fun getLatestReleaseTag(filter: VersionFilter = any): VersionTag? { return getAllVersionTags(filter).filter { it.version is Release }.maxOrNull() } private fun getAllVersionTags(filter: VersionFilter): List<VersionTag> { val tagFilter = { tag: VersionTag -> filter(tag.version) } return git( listOf( "for-each-ref", "--merged", "HEAD", "--sort=-committerdate", "--format=%(refname:short)", "refs/tags/*.*.*" ) ).mapNotNull { VersionTag.versionTag(it) }.filter(tagFilter) } fun getLogX(from: TagName? = null, to: TagName? = null): List<GitCommit> { val end = to?.toString() ?: "HEAD" val arguments = listOf("log", "--format=format:%H %aI%n%B%n%x1E", from?.let { "$it..$end" } ?: end ) val result = git(arguments) return result.joinToString("\n").split(RECORD_SEPARATOR).map(String::trim).mapNotNull { Regex("^(\\S+) (\\S+)\\n").matchAt(it, 0)?.let { match -> val (hash, date) = match.destructured GitCommit( hash = hash, date = ZonedDateTime(date), message = it.substring(match.range.last + 1) ) } } } private fun git(arguments: List<String>, success: (SystemCallResult) -> Boolean = { it.code == 0 }): List<String> { val result = sys.call("git", arguments) if (success(result)) { return result.stdout } else { throw RuntimeException("unexpected result from system call (git $arguments): $result") } } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/git/Git.kt
3498903309
package de.fruiture.cor.ccs.git import de.fruiture.cor.ccs.cc.Body import de.fruiture.cor.ccs.cc.ConventionalCommitMessage import de.fruiture.cor.ccs.cc.Description import de.fruiture.cor.ccs.cc.Type import de.fruiture.cor.ccs.semver.Version import kotlinx.serialization.EncodeDefault import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import kotlin.jvm.JvmInline @JvmInline @Serializable value class ZonedDateTime(private val iso8601: String) { override fun toString() = iso8601 } val NON_CONVENTIONAL_COMMIT_TYPE = Type("none") @Serializable data class GitCommit( val hash: String, val date: ZonedDateTime, val message: String ) { @OptIn(ExperimentalSerializationApi::class) @EncodeDefault val conventional = runCatching { ConventionalCommitMessage.message(message) }.getOrElse { val lines = message.lines() val bodyText = lines.dropLast(1).joinToString("\n").trim() ConventionalCommitMessage( type = NON_CONVENTIONAL_COMMIT_TYPE, description = Description(lines.first()), body = if (bodyText.isNotBlank()) Body(bodyText) else null ) } val type = conventional.type val hasBreakingChange = conventional.hasBreakingChange } @JvmInline value class TagName(val value: String) { override fun toString() = value } data class VersionTag(val tag: TagName, val version: Version) : Comparable<VersionTag> { init { require(tag.value.contains(version.toString())) { "tag '$tag' does not contain version number '$version'" } } override fun compareTo(other: VersionTag) = version.compareTo(other.version) override fun toString() = tag.toString() companion object { fun versionTag(tagName: String) = Version.extractVersion(tagName)?.let { VersionTag(TagName(tagName), it) } } }
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/git/GitCommit.kt
1354227209
package de.fruiture.cor.ccs.git interface SystemCaller { fun call(command: String, arguments: List<String> = emptyList()): SystemCallResult } data class SystemCallResult( val code: Int, val stdout: List<String> = emptyList(), val stderr: List<String> = emptyList() )
git-ccs/src/commonMain/kotlin/de/fruiture/cor/ccs/git/SystemCaller.kt
3201990921
package com.example.aplikasiteman import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.aplikasiteman", appContext.packageName) } }
TugasPPB/app/src/androidTest/java/com/example/aplikasiteman/ExampleInstrumentedTest.kt
3728867410
package com.example.aplikasiteman import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
TugasPPB/app/src/test/java/com/example/aplikasiteman/ExampleUnitTest.kt
1128709288
package com.example.aplikasiteman import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.Toast import com.example.aplikasiteman.databinding.ActivityMainBinding import com.firebase.ui.auth.AuthUI import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase class MainActivity : AppCompatActivity(), View.OnClickListener { private var auth:FirebaseAuth? = null private val RC_SIGN_IN = 1 private lateinit var binding : ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) //inisiasi ID (button) binding.logout.setOnClickListener(this) binding.save.setOnClickListener(this) binding.showData.setOnClickListener(this) //mendapatkan Instance Firebase Autentikasi auth = FirebaseAuth.getInstance() } private fun isEmpty(s: String): Boolean { return TextUtils.isEmpty(s) } override fun onClick(p0: View?) { when (p0?.getId()) { R.id.save -> { //Mendapatkan UserID dari pengguna yang terauth val getUserID = auth!!.currentUser!!.uid //Mendapatkan instance dari Database val database = FirebaseDatabase.getInstance() //Mendapatkan Data yang diinputkan User ke dalam variabel val getNama: String = binding.nama.getText().toString() val getAlamat: String = binding.alamat.getText().toString() val getNoHP: String = binding.noHp.getText().toString() //Mendapatkan referensi dari database val getReference: DatabaseReference getReference = database.reference //mengecek apakah ada data yang kosong if (isEmpty(getNama) || isEmpty(getAlamat) || isEmpty(getNoHP)) { //Jika ada, maka akan menampilkan pesan singkat seperti berikut Toast.makeText( this@MainActivity, "Data tidak boleh ada yang kosong", Toast.LENGTH_SHORT).show() } else { //Jika tidak ada, maka menyimpan ke databse sesuai ID masing-masing akun getReference.child("Admin").child(getUserID).child("DataTeman").push() .setValue(data_teman(getNama, getAlamat, getNoHP)) .addOnCompleteListener(this) { //bagian isi terjadi ketika user berhasil menyimpan data binding.nama.setText("") binding.alamat.setText("") binding.noHp.setText("") Toast.makeText(this@MainActivity, "Data Tersimpan", Toast.LENGTH_SHORT).show() } } } R.id.logout -> { AuthUI.getInstance().signOut(this) .addOnCompleteListener(object : OnCompleteListener<Void> { override fun onComplete(p0: Task<Void>) { Toast.makeText(this@MainActivity, "Logout Berhasil", Toast.LENGTH_SHORT).show() intent = Intent(applicationContext, LoginActivity::class.java) startActivity(intent) finish() } }) } R.id.show_data -> { startActivity(Intent(this@MainActivity, MyListData::class.java)) } } } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/MainActivity.kt
1469467048
package com.example.aplikasiteman import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.Toast import com.example.aplikasiteman.databinding.ActivityUpdateDataBinding import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase class UpdateData : AppCompatActivity() { //deklarasikan variabel private var database: DatabaseReference? = null private var auth: FirebaseAuth? = null private var cekNama: String? = null private var cekAlamat: String? = null private var cekNoHP: String? = null private lateinit var binding: ActivityUpdateDataBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityUpdateDataBinding.inflate(layoutInflater) setContentView(binding.root) supportActionBar?.title = "Update Data" //mendapatkan instance otentikasi dan refrensi dari DB auth = FirebaseAuth.getInstance() database = FirebaseDatabase.getInstance().reference data // memanggil method data binding.update.setOnClickListener { //mendapatkan data teman yang akan dicek cekNama = binding.newNama.text.toString() cekAlamat = binding.newAlamat.text.toString() cekNoHP = binding.newNohp.text.toString() //mengecek agar tidak ada yang kosong if ( isEmpty(cekNama!!) || isEmpty(cekAlamat!!) || isEmpty(cekNoHP!!)) { Toast.makeText(this@UpdateData, "Data tidak boleh kosong", Toast.LENGTH_SHORT).show() } else { //menjalankan update data val setTeman = data_teman() setTeman.nama = binding.newNama.text.toString() setTeman.alamat = binding.newAlamat.text.toString() setTeman.no_hp = binding.newNohp.text.toString() updateTeman(setTeman) } } } //mengecek apakah ada data kosong private fun isEmpty(s: String): Boolean { return TextUtils.isEmpty(s) } //menampilkan data yang akan diupdate private val data: Unit private get() { //menampilkan data dari item yang sudah dipilih val getNama = intent.getStringExtra("dataNama") val getAlamat = intent.getStringExtra("dataAlamat") val getNoHP = intent.getStringExtra("dataNoHP") binding.newNama.setText(getNama) binding.newAlamat.setText(getAlamat) binding.newNohp.setText(getNoHP) } //proses update private fun updateTeman(teman: data_teman) { val userID = auth!!.uid val getKey = intent.getStringExtra("getPrimaryKey") database!!.child("Admin") .child(userID!!) .child("DataTeman") .child(getKey!!) .setValue(teman) .addOnSuccessListener { binding.newNama.setText("") binding.newAlamat.setText("") binding.newNohp.setText("") Toast.makeText(this@UpdateData, "Data berhasil diupdate", Toast.LENGTH_SHORT).show() finish() } } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/UpdateData.kt
505561647
package com.example.aplikasiteman class data_teman { //deklarasi variabel var nama : String? = null var alamat : String? = null var no_hp : String? = null var key : String? = null //Membuat constructor kosong untuk membaca data snapshot constructor() {} //Konstruktor dengan beberapa parameter, untuk mendapatkan Input Data dari User constructor(nama: String?, alamat: String?, no_hp: String?) { this.nama = nama this.alamat = alamat this.no_hp = no_hp } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/data_teman.kt
3508904898
package com.example.aplikasiteman import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.core.content.ContextCompat import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.aplikasiteman.databinding.ActivityMyListDataBinding import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class MyListData : AppCompatActivity() { //deklarasikan variabel ubtuk RC private var recyclerView : RecyclerView? = null private var adapter: RecyclerView.Adapter<*>? = null private var layoutManager: RecyclerView.LayoutManager? = null //deklarasi variabel DB Refrence & Arraylist dengan parameter ClassModel val database = FirebaseDatabase.getInstance() private var DataTeman = ArrayList<data_teman>() private var auth: FirebaseAuth? = null private lateinit var binding: ActivityMyListDataBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMyListDataBinding.inflate(layoutInflater) setContentView(binding.root) recyclerView = findViewById(R.id.datalist) setSupportActionBar(findViewById(R.id.my_toolbar)) supportActionBar!!.title = "Data Teman" auth = FirebaseAuth.getInstance() MyRecyclerView() GetData() } //kode untuk mengambil data databse & menamplikan ke dalam adapter private fun GetData(){ Toast.makeText(applicationContext, "Mohon tunggu sebentar...", Toast.LENGTH_LONG).show() val getUserID: String = auth?.getCurrentUser()?.getUid().toString() val getReference = database.getReference() getReference.child("Admin").child(getUserID).child("DataTeman") .addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()){ DataTeman.clear() for (snapshot in dataSnapshot.children) { //mapping data pada DataSnapshot ke dalam objek DataTeman val teman = snapshot.getValue(data_teman::class.java) //mengambil Primaary Key untuk proses update/delete teman?.key = snapshot.key DataTeman.add(teman!!) } //Inisialisasi adapter dan data teman dalam bentuk array adapter = RecyclerViewAdapter(DataTeman, this@MyListData) //memasang adapter pada RC recyclerView?.adapter = adapter (adapter as RecyclerViewAdapter).notifyDataSetChanged() Toast.makeText(applicationContext, "Data berhasil dimuat", Toast.LENGTH_LONG).show() } } override fun onCancelled(databaseError: DatabaseError) { //kode ini dijalankan ketika error, disimpan ke logcat Toast.makeText(applicationContext, "Data Gagal dimuat", Toast.LENGTH_LONG).show() Log.e("MyListActivity", databaseError.details +" "+ databaseError.message) } }) } //baris kode untuk mengatur RC private fun MyRecyclerView(){ layoutManager = LinearLayoutManager(this) recyclerView?.layoutManager = layoutManager recyclerView?.setHasFixedSize(true) //buat garis bawah setiap item data val itemDecoration = DividerItemDecoration(applicationContext, DividerItemDecoration.VERTICAL) itemDecoration.setDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.line)!!) recyclerView?.addItemDecoration(itemDecoration) } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/MyListData.kt
3448120670
package com.example.aplikasiteman import android.annotation.SuppressLint import android.app.AlertDialog import android.app.LauncherActivity.ListItem import android.content.Context import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase class RecyclerViewAdapter (private val DataTeman: ArrayList<data_teman>, context: Context) : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> () { private val context: Context //view holder digunakan untuk menyimpan referensi daro view-view inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val Nama: TextView val Alamat: TextView val NoHP: TextView val ListItem: LinearLayout //meninisialisasi view yang terpasang pada layout RecyclerView init { Nama = itemView.findViewById(R.id.namax) Alamat = itemView.findViewById(R.id.alamatx) NoHP = itemView.findViewById(R.id.no_hpx) ListItem = itemView.findViewById(R.id.list_item) } } init { this.context = context } //membuat view untuk menyiapkan dan memasang layout yg digunakan pada RecyclerView override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val V: View = LayoutInflater.from(parent.getContext()).inflate( R.layout.view_design, parent, false ) return ViewHolder(V) } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) { val Nama: String? = DataTeman.get(position).nama val Alamat: String? = DataTeman.get(position).alamat val NoHP: String? = DataTeman.get(position).no_hp //masukkan nilai atau value ke dalam view holder.Nama.text = "Nama: $Nama" holder.Alamat.text = "Alamat: $Alamat" holder.NoHP.text = "No Handphone: $NoHP" //membuat fungsi edit dan delete holder.ListItem.setOnLongClickListener { view -> val action = arrayOf("Update", "Delete") val alertDialogBuilder= AlertDialog.Builder(view.context) alertDialogBuilder.setItems(action) { dialog, i -> when (i) { 0 -> { //berpindah ke halaman update val bundle = Bundle().apply { putString("dataNama", DataTeman[position].nama) putString("dataAlamat", DataTeman[position].nama) putString("dataNoHP", DataTeman[position].no_hp) putString("getPrimaryKey", DataTeman[position].key) } val intent = Intent(view.context, UpdateData::class.java).apply { putExtras(bundle) } context.startActivity(intent) } 1 -> { deleteData(position) } } } alertDialogBuilder.create().show() true } } //menghitung Ukuran/jumlah Data yng akan ditampilkan pada RC override fun getItemCount(): Int { return DataTeman.size } private fun deleteData(position: Int) { val database = FirebaseDatabase.getInstance().reference val userID = FirebaseAuth.getInstance().currentUser?.uid val key = DataTeman[position].key if (userID != null && key != null) { database.child("Admin").child(userID).child("DataTeman").child(key) .removeValue() } } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/RecyclerViewAdapter.kt
2350423717
package com.example.aplikasiteman import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.example.aplikasiteman.databinding.ActivityLoginBinding import com.firebase.ui.auth.AuthUI import com.firebase.ui.auth.IdpResponse import com.google.firebase.auth.FirebaseAuth class LoginActivity : AppCompatActivity(), View.OnClickListener { private var auth: FirebaseAuth? = null private val RC_SIGN_IN = 1 private lateinit var binding : ActivityLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding.root) binding.progress.visibility = View.GONE binding.login.setOnClickListener(this) auth = FirebaseAuth.getInstance() if (auth!!.currentUser == null) { } else { intent = Intent(applicationContext, MainActivity::class.java) startActivity(intent) finish() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RC_SIGN_IN) { val response = IdpResponse.fromResultIntent(data) if (resultCode == Activity.RESULT_OK) { val user = FirebaseAuth.getInstance().currentUser Toast.makeText(this, "Login Berhasil", Toast.LENGTH_SHORT).show() startActivity(intent) finish() } else { Toast.makeText(this, "Login Dibatalkan", Toast.LENGTH_SHORT).show() } } } override fun onClick(v: View?) { val provider = arrayListOf(AuthUI.IdpConfig.GoogleBuilder().build()) startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setAvailableProviders(provider) .build(), RC_SIGN_IN) } }
TugasPPB/app/src/main/java/com/example/aplikasiteman/LoginActivity.kt
3903512873
package example.com class ApplicationTest { }
countries-server/src/test/kotlin/example/com/ApplicationTest.kt
856673311
package example.com.fake import example.com.models.ApiResponse import example.com.models.Country import example.com.repository.CountryRepository class FakeCountryRepository : CountryRepository{ override var countries: Map<Int, List<Country>> = FakeCountryDataSource().createFakeCountriesDataSource() override var pageCount: Int = countries.size override suspend fun getCountries(page: Int): ApiResponse { val (prevPage, nextPage) = calculatePage(page) return ApiResponse( success = true, message = "ok", prevPage = prevPage, nextPage = nextPage, countries = countries[page-1]!! // Adjusting for zero-based array index (page - 1) ) } private fun calculatePage(page: Int): Pair<Int?, Int?> { val prevPage = if (page in 2..pageCount) page - 1 else null val nextPage = if (page in 1 until pageCount) page + 1 else null return Pair(prevPage, nextPage) } }
countries-server/src/test/kotlin/example/com/fake/FakeCountryRepository.kt
3031977076
package example.com.fake import example.com.models.* class FakeCountryDataSource { fun createFakeCountriesDataSource(): Map<Int, List<Country>> { return listOf( createFakeCountry("Country1", "Flag1", "SVG1", "Alt1"), createFakeCountry("Country2", "Flag2", "SVG2", "Alt2"), createFakeCountry("Country3", "Flag3", "SVG3", "Alt3"), createFakeCountry("Country4", "Flag4", "SVG4", "Alt4"), createFakeCountry("Country5", "Flag5", "SVG5", "Alt5"), createFakeCountry("Country6", "Flag6", "SVG6", "Alt6"), ).chunked(2).withIndex().associate { (index, list) -> index to list } } private fun createFakeCountry( name: String, flagAlt: String, flagSvg: String, flagPng: String ): Country { return Country( flags = Flag( png = flagPng, svg = flagSvg, alt = flagAlt ), name = Name( common = name, official = "Official $name", nativeName = mapOf( "en" to NativeName( official = "Official English Name $name", common = "Common English Name $name" ) ) ), currencies = mapOf( "USD" to Currencies( name = "US Dollar", symbol = "$" ) ), capital = listOf("Capital $name"), region = "Region $name", subregion = "Subregion $name", languages = mapOf( "en" to "English", "fr" to "French" // Add more language mappings as needed ), population = 1000000, // Replace with the desired population value borders = listOf("Border1", "Border2") // Add more fields as needed ) } }
countries-server/src/test/kotlin/example/com/fake/FakeCountryDataSource.kt
4168573780
package example.com.routes import example.com.base.BaseRoutingTest import example.com.fake.FakeCountryRepository import example.com.models.ApiResponse import example.com.repository.CountryRepository import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.routing.* import kotlinx.serialization.json.Json import org.junit.Before import org.koin.dsl.module import kotlin.test.Test import kotlin.test.assertEquals class GetAllCountriesTest : BaseRoutingTest() { private val countryRepository: CountryRepository = FakeCountryRepository() @Before fun setup() { testModule = module { single { countryRepository } } testRouting = { install(Routing) { getAllCountries() } } } @Test fun `access countries endpoint, with valid page query, assert correct response`() = withBaseTestApplication { val pageQuery = 3 client.get("/countries?page=$pageQuery").apply { val actual = Json.decodeFromString<ApiResponse>(this.bodyAsText()) val expected = countryRepository.getCountries(pageQuery) assertEquals(HttpStatusCode.OK, status) assertEquals(actual, expected) } } @Test fun `access countries endpoint, with non-numeric page query, assert error`() = withBaseTestApplication { client.get("/countries?page=").apply { val actual = Json.decodeFromString<ApiResponse>(this.bodyAsText()) val expected = ApiResponse( success = false, message = "Only Numbers Allowed." ) assertEquals(HttpStatusCode.BadRequest, status) assertEquals(expected, actual) } } @Test fun `access countries endpoint, with invalid page size, assert error`() = withBaseTestApplication { client.get("/countries?page=${countryRepository.pageCount + 1}").apply { val actual = Json.decodeFromString<ApiResponse>(this.bodyAsText()) val expected = ApiResponse( success = false, message = "Countries not Found." ) assertEquals(HttpStatusCode.NotFound, status) assertEquals(expected, actual) } } }
countries-server/src/test/kotlin/example/com/routes/GetAllCountriesTest.kt
526237988
package example.com.routes import example.com.base.BaseRoutingTest import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.routing.* import io.ktor.server.testing.* import kotlinx.serialization.ExperimentalSerializationApi import org.junit.Before import kotlin.test.Test import kotlin.test.assertEquals class RootTest : BaseRoutingTest(){ @Before fun setup() { testRouting = { install(Routing) { root() } } } @Test fun `access root endpoint assert correct information`() = withBaseTestApplication{ client.get("/").apply { assertEquals(HttpStatusCode.OK, status) assertEquals("Welcome to Countries API!", bodyAsText()) } } @ExperimentalSerializationApi @Test fun `access non existing endpoint,assert not found`() = testApplication { val response = client.get("/unknown") assertEquals(expected = HttpStatusCode.NotFound, actual = response.status) assertEquals(expected = "Page not Found.", actual = response.bodyAsText()) } }
countries-server/src/test/kotlin/example/com/routes/RootTest.kt
2183370798
package example.com.base import example.com.plugins.configureSerialization import io.ktor.server.application.* import io.ktor.server.config.* import io.ktor.server.testing.* import org.koin.core.context.GlobalContext.stopKoin import org.koin.core.module.Module import org.koin.ktor.plugin.Koin abstract class BaseRoutingTest { protected var testModule: Module? = null protected var testRouting: Application.() -> Unit = { } init { stopKoin() } fun <R> withBaseTestApplication(test: suspend ApplicationTestBuilder.() -> R) = testApplication { environment { config = MapApplicationConfig("ktor.environment" to "test") } application { testModule?.let { install(Koin) { modules(it) } configureSerialization() } testRouting() } test() } }
countries-server/src/test/kotlin/example/com/base/BaseRoutingTest.kt
3059062234
package example.com.repository import example.com.models.ApiResponse import example.com.models.Country interface CountryRepository { val pageCount: Int val countries: Map<Int, List<Country>> suspend fun getCountries(page: Int = 1): ApiResponse }
countries-server/src/main/kotlin/example/com/repository/CountryRepository.kt
955522295
package example.com.repository import example.com.models.ApiResponse import example.com.models.Country import kotlinx.serialization.json.Json import java.io.File const val PAGE_SIZE = 10 class CountryRepositoryImpl : CountryRepository { override var countries: Map<Int, List<Country>> override var pageCount: Int init { countries = fetchCountriesFromFileConvertToMap( "/Users/ahmetfurkansevim/Desktop/ktor/countries-server/src/main/resources/countries.json" ) pageCount = countries.size } override suspend fun getCountries(page: Int): ApiResponse { val (prevPage, nextPage) = calculatePage(page) return ApiResponse( success = true, message = "ok", prevPage = prevPage, nextPage = nextPage, countries = countries[page-1]!! // Adjusting for zero-based array index (page - 1) ) } private fun fetchCountriesFromFileConvertToMap(filePath: String): Map<Int, List<Country>> { try { val json = File(filePath).readText() val content = Json.decodeFromString<List<Country>>(json) return content.chunked(PAGE_SIZE).withIndex().associate { (index, list) -> index to list } } catch (e: Exception) { // Log the exception or handle it appropriately throw RuntimeException("Failed to fetch countries from file.", e) } } private fun calculatePage(page: Int): Pair<Int?, Int?> { val prevPage = if (page in 2..pageCount) page - 1 else null val nextPage = if (page in 1 until pageCount) page + 1 else null return Pair(prevPage, nextPage) } }
countries-server/src/main/kotlin/example/com/repository/CountryRepositoryImpl.kt
3562850444
package example.com.di import example.com.repository.CountryRepository import example.com.repository.CountryRepositoryImpl import org.koin.dsl.module val koinModule = module { single<CountryRepository> { CountryRepositoryImpl() } }
countries-server/src/main/kotlin/example/com/di/KoinModule.kt
382378058
package example.com import example.com.plugins.* import io.ktor.server.application.* fun main(args: Array<String>) = io.ktor.server.netty.EngineMain.main(args) fun Application.module() { configureKoin() configureDefaultHeader() configureSerialization() configureMonitoring() configureRouting() configureStatusPages() }
countries-server/src/main/kotlin/example/com/Application.kt
2232139715
package example.com.plugins import example.com.routes.getAllCountries import example.com.routes.root import io.ktor.server.application.* import io.ktor.server.routing.* fun Application.configureRouting() { routing { root() getAllCountries() } }
countries-server/src/main/kotlin/example/com/plugins/Routing.kt
111307526
package example.com.plugins import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.defaultheaders.* fun Application.configureDefaultHeader() { install(DefaultHeaders) { val oneYearInSeconds = java.time.Duration.ofDays(365).seconds header( name = HttpHeaders.CacheControl, value = "public, max-age=$oneYearInSeconds, immutable" ) } }
countries-server/src/main/kotlin/example/com/plugins/DefaultHeaders.kt
3580199622
package example.com.plugins import io.ktor.serialization.kotlinx.json.* import io.ktor.server.application.* import io.ktor.server.plugins.contentnegotiation.* fun Application.configureSerialization() { install(ContentNegotiation) { json() } }
countries-server/src/main/kotlin/example/com/plugins/Serialization.kt
1708166843
package example.com.plugins import example.com.di.koinModule import io.ktor.server.application.* import org.koin.ktor.plugin.Koin import org.koin.logger.slf4jLogger fun Application.configureKoin() { install(Koin) { slf4jLogger() modules(koinModule) } }
countries-server/src/main/kotlin/example/com/plugins/Koin.kt
3989498826
package example.com.plugins import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.response.* fun Application.configureStatusPages() { install(StatusPages) { status(HttpStatusCode.NotFound) { call, _ -> call.respond( message = "Page not Found.", status = HttpStatusCode.NotFound ) } } }
countries-server/src/main/kotlin/example/com/plugins/StatusPage.kt
4189587939
package example.com.plugins import io.ktor.server.application.* import io.ktor.server.plugins.callloging.* fun Application.configureMonitoring() { install(CallLogging) }
countries-server/src/main/kotlin/example/com/plugins/Monitoring.kt
3599556082
package example.com.models import kotlinx.serialization.Serializable @Serializable data class Country( val flags: Flag, val name: Name, val currencies: Map<String, Currencies>, val capital: List<String>, val region: String, val subregion: String, val languages: Map<String, String>, val population: Int, val borders: List<String> ) @Serializable data class Flag( val png: String, val svg: String, val alt: String ) @Serializable data class NativeName( val official: String, val common: String ) @Serializable data class Name( val common: String, val official: String, val nativeName: Map<String, NativeName> ) @Serializable data class Currencies( val name: String, val symbol: String ) @Serializable data class Language( val code: String, val name: String )
countries-server/src/main/kotlin/example/com/models/Country.kt
3494280079
package example.com.models import kotlinx.serialization.Serializable @Serializable data class ApiResponse( val success: Boolean, val message: String? = null, val prevPage: Int? = null, val nextPage: Int? = null, val countries: List<Country> = emptyList() )
countries-server/src/main/kotlin/example/com/models/ApiResponse.kt
2067181215
package example.com.routes import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Route.root() { get("/") { call.respond( message = "Welcome to Countries API!", status = HttpStatusCode.OK ) } }
countries-server/src/main/kotlin/example/com/routes/Root.kt
1400361153
package example.com.routes import example.com.models.ApiResponse import example.com.repository.CountryRepository import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* import org.koin.ktor.ext.inject fun Route.getAllCountries() { val countryRepository: CountryRepository by inject() get("/countries") { try { val page = call.request.queryParameters["page"]?.toInt() ?: 1 require(page in 1..countryRepository.pageCount) val apiResponse = countryRepository.getCountries(page) call.respond( message = apiResponse, status = HttpStatusCode.OK ) } catch (e: NumberFormatException) { call.respond( message = ApiResponse(success = false, message = "Only Numbers Allowed."), status = HttpStatusCode.BadRequest ) } catch (e: IllegalArgumentException) { call.respond( message = ApiResponse(success = false, message = "Countries not Found."), status = HttpStatusCode.NotFound ) } } }
countries-server/src/main/kotlin/example/com/routes/GetAllCountries.kt
3768436109
package com.langdroid.core import com.langdroid.core.models.GenerativeModel import com.langdroid.core.models.GenerativeModelApiActions import com.langdroid.core.models.request.config.GenerativeConfig import kotlinx.coroutines.flow.Flow public class LangDroidModelActions<M : GenerativeModel>( private val model: M, config: GenerativeConfig<M>? ) : GenerativeModelApiActions { init { model.config = config } public override suspend fun generateText(prompt: String): Result<String> = generateText(createSimplePrompt(prompt)) public override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> = model.actions.generateText(prompts) public override suspend fun generateTextStream(prompt: String): Result<Flow<String?>> = generateTextStream(createSimplePrompt(prompt)) public override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> = model.actions.generateTextStream(prompts) public override suspend fun sanityCheck(): Boolean = model.actions.sanityCheck() public override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> = model.actions.calculateTokens(prompts) private fun createSimplePrompt(prompt: String): List<ChatPrompt> = listOf(ChatRole.User to prompt) }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/LangDroidModelActions.kt
3849046894
package com.langdroid.core internal inline fun <T> actionWithResult( noinline specificExceptionHandler: ((Exception) -> Result<T>)? = null, block: () -> T ): Result<T> { return try { Result.success(block()) } catch (e: Exception) { // Check if a specific exception handler is provided and use it specificExceptionHandler?.invoke(e) ?: Result.failure(e) } }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/utils.kt
1654205365
package com.langdroid.core @JvmInline public value class ChatRole(public val role: String) { public companion object { public val System: ChatRole = ChatRole("system") public val User: ChatRole = ChatRole("user") public val Assistant: ChatRole = ChatRole("assistant") public val Function: ChatRole = ChatRole("function") public val Tool: ChatRole = ChatRole("tool") public val Model: ChatRole = ChatRole("model") } } public typealias ChatPrompt = Pair<ChatRole, String?>
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/ChatRole.kt
2034644325
package com.langdroid.core.models.gemini import com.langdroid.core.ChatPrompt import com.langdroid.core.models.GenerativeModelActions import kotlinx.coroutines.flow.Flow @Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING") public expect class GeminiModelActions(model: GeminiModel) : GenerativeModelActions { internal val model: GeminiModel override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> override suspend fun sanityCheck(): Boolean override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/gemini/GeminiModelActions.kt
1651375600
package com.langdroid.core.models.gemini import com.langdroid.core.models.GenerativeModel import com.langdroid.core.models.GenerativeModelActions public sealed class GeminiModel( override val id: String, override val tokenLimit: Int, override val outputTokenLimit: Int? = null ) : GenerativeModel() { private val modelActions: GenerativeModelActions by lazy { GeminiModelActions(this) } public override val actions: GenerativeModelActions = modelActions public data class Pro(override val apiKey: String?) : GeminiModel( id = "models/gemini-pro", tokenLimit = GEMINI_TOKEN_LIMIT, outputTokenLimit = GEMINI_TOKEN_OUTPUT_LIMIT ) public data class Ultra(override val apiKey: String?) : GeminiModel( id = "models/gemini-ultra", tokenLimit = GEMINI_TOKEN_LIMIT, outputTokenLimit = GEMINI_TOKEN_OUTPUT_LIMIT ) public data class Custom( override val id: String, override val apiKey: String?, override val tokenLimit: Int = GEMINI_TOKEN_LIMIT, override val outputTokenLimit: Int? = GEMINI_TOKEN_OUTPUT_LIMIT, ) : GeminiModel(id, tokenLimit, outputTokenLimit) } private const val GEMINI_TOKEN_OUTPUT_LIMIT = 2048 private const val GEMINI_TOKEN_LIMIT = 30720 + GEMINI_TOKEN_OUTPUT_LIMIT
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/gemini/GeminiModel.kt
1643683370
package com.langdroid.core.models.gemini import com.langdroid.core.models.request.config.fields.RequestConfigFields public class GeminiRequestConfigFields( override val maxOutputTokens: String = "maxOutputTokens", override val temperature: String = "temperature", override val topP: String? = "topP", override val topK: String? = "topK", override val configObjectName: String? = "generationConfig" ) : RequestConfigFields
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/gemini/GeminiRequestConfigFields.kt
2624503780
package com.langdroid.core.models import com.langdroid.core.ChatPrompt import kotlinx.coroutines.flow.Flow public interface GenerativeModelActions { public suspend fun generateText(prompts: List<ChatPrompt>): Result<String> public suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> public suspend fun sanityCheck(): Boolean public suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/GenerativeModelActions.kt
4246871982
package com.langdroid.core.models import kotlinx.coroutines.flow.Flow public interface GenerativeModelApiActions : GenerativeModelActions { public suspend fun generateText(prompt: String): Result<String> public suspend fun generateTextStream(prompt: String): Result<Flow<String?>> }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/GenerativeModelApiActions.kt
531818099
package com.langdroid.core.models.request.config.fields public interface RequestConfigFields { public val maxOutputTokens: String? /** * Defines the wrapping object name for LLM API request configurations. * * - `configObjectName`: The name of the outer object (e.g., "generationConfig"). If provided, configuration settings like * `temperature`, `topP`, `topK`, and `maxOutputTokens` are nested within. If `null`, settings are at the top level, adapting to APIs with different structuring needs. */ public val configObjectName: String? public val temperature: String? public val topP: String? public val topK: String? }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/request/config/fields/RequestConfigFields.kt
1759085569
package com.langdroid.core.models.request.config.fields // Maybe make all fields equal to null public class DefaultRequestConfigFields( override val maxOutputTokens: String = "max_tokens", override val temperature: String = "temperature", override val topP: String? = "top_p", override val topK: String? = "top_k", override val configObjectName: String? = null ) : RequestConfigFields
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/request/config/fields/DefaultRequestConfigFields.kt
3532348790
package com.langdroid.core.models.request.config import com.langdroid.core.models.GenerativeModel public interface GenerativeConfig<M : GenerativeModel> { public val temperature: Float? public val topP: Float? public val topK: Int? public val maxOutputTokens: Int? public companion object { public inline fun <reified M : GenerativeModel> create(onCreate: Builder<M>.() -> Unit = {}): GenerativeConfig<M> { // val requestConfigFields = when (M::class) { // OpenAiModel::class -> OpenAiRequestConfigFields() // GeminiModel::class -> GeminiRequestConfigFields() // else -> DefaultRequestConfigFields() // } val builder = Builder<M>() onCreate(builder) return builder.build() } } public class Builder<M : GenerativeModel> { public var temperature: Float? = null public var topP: Float? = null public var topK: Int? = null public var maxOutputTokens: Int? = null public fun temperature(temperature: Float): Builder<M> = apply { this.temperature = temperature } public fun topP(topP: Float): Builder<M> = apply { this.topP = topP } public fun topK(topK: Int): Builder<M> = apply { this.topK = topK } public fun maxOutputTokens(maxOutputTokens: Int): Builder<M> = apply { this.maxOutputTokens = maxOutputTokens } public fun build(): GenerativeConfig<M> = object : GenerativeConfig<M> { override val temperature: Float? = [email protected] override val topP: Float? = [email protected] override val topK: Int? = [email protected] override val maxOutputTokens: Int? = [email protected] } } }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/request/config/GenerativeConfig.kt
907016658
package com.langdroid.core.models import com.langdroid.core.models.request.config.GenerativeConfig public abstract class GenerativeModel { public abstract val apiKey: String? // Name of model public abstract val id: String // Max amount of tokens available for model to handle public abstract val tokenLimit: Int public abstract val outputTokenLimit: Int? internal var config: GenerativeConfig<*>? = null internal abstract val actions: GenerativeModelActions }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/GenerativeModel.kt
1896238529
package com.langdroid.core.models.openai import com.aallam.openai.api.chat.ChatMessage import com.aallam.openai.api.core.Role import com.langdroid.core.ChatPrompt import com.langdroid.core.ChatRole internal fun ChatPrompt.toOpenAIPrompt(): ChatMessage = ChatMessage( role = first.toOpenAIChatRole(), content = second ) private fun ChatRole.toOpenAIChatRole() = Role(this.role)
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/transform.kt
3604240317
package com.langdroid.core.models.openai import com.langdroid.core.models.GenerativeModel import com.langdroid.core.models.GenerativeModelActions public sealed class OpenAiModel( override val id: String, override val tokenLimit: Int, override val outputTokenLimit: Int? = null ) : GenerativeModel() { private val modelActions: GenerativeModelActions by lazy { OpenAiModelActions(this) } public override val actions: GenerativeModelActions = modelActions /* gpt-3.5-turbo-0125 - The latest GPT-3.5 Turbo model with higher accuracy at responding in requested formats and a fix for a bug which caused a text encoding issue for non-English language function calls. */ public data class Gpt3_5(override val apiKey: String?) : OpenAiModel( // Same as gpt-3.5-turbo id = "gpt-3.5-turbo-0125", tokenLimit = GPT3_5_TOKEN_LIMIT, outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT ) /* gpt-4 - Currently points to gpt-4-0613. Snapshot of GPT-4 from June 13th 2023 with improved function calling support. Training data up to Sep 2021. */ public data class Gpt4(override val apiKey: String?) : OpenAiModel( id = "gpt-4", tokenLimit = GPT4_TOKEN_LIMIT, outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT ) // OTHER MODELS /* gpt-3.5-turbo-1106 - GPT-3.5 Turbo model with improved instruction following, JSON mode, reproducible outputs, parallel function calling, and more. */ public data class Gpt3_5Plus(override val apiKey: String?) : OpenAiModel( id = "gpt-3.5-turbo-1106", tokenLimit = GPT3_5_TOKEN_LIMIT, outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT ) /* gpt-4-0125-preview - The latest GPT-4 model intended to reduce cases of “laziness” where the model doesn’t complete a task. Training data up to Dec 2023. */ public data class Gpt4_128kNoLazy(override val apiKey: String?) : OpenAiModel( id = "gpt-4-0125-preview", tokenLimit = GPT_128K_TOKEN_LIMIT, outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT ) /* gpt-4-1106-preview - GPT-4 Turbo model featuring improved instruction following, JSON mode, reproducible outputs, parallel function calling, and more. Training data up to Apr 2023. */ public data class Gpt4_128kPlus(override val apiKey: String?) : OpenAiModel( id = "gpt-4-1106-preview", tokenLimit = GPT_128K_TOKEN_LIMIT, outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT ) /* gpt-4-32k - Currently points to gpt-4-32k-0613. Snapshot of gpt-4-32k from June 13th 2023 with improved function calling support. This model was never rolled out widely in favor of GPT-4 Turbo. Training data up to Sep 2021. */ public data class Gpt4_32k(override val apiKey: String?) : OpenAiModel( id = "gpt-4-32k", tokenLimit = GPT_32K_TOKEN_LIMIT, outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT ) public data class Custom( override val id: String, override val apiKey: String?, override val tokenLimit: Int = CUSTOM_MODEL_TOKEN_LIMIT, override val outputTokenLimit: Int? = GPT_TOKEN_OUTPUT_LIMIT, ) : OpenAiModel(id, tokenLimit, outputTokenLimit) } private const val CUSTOM_MODEL_TOKEN_LIMIT = 4096 private const val GPT4_TOKEN_LIMIT = 8192 private const val GPT3_5_TOKEN_LIMIT = 16385 private const val GPT_TOKEN_OUTPUT_LIMIT = 4096 private const val GPT_128K_TOKEN_LIMIT = 128000 private const val GPT_32K_TOKEN_LIMIT = 32768
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/OpenAiModel.kt
4119622322
package com.langdroid.core.models.openai import com.langdroid.core.models.request.config.fields.RequestConfigFields public class OpenAiRequestConfigFields( override val maxOutputTokens: String = "max_tokens", override val temperature: String = "temperature", override val topP: String? = "top_p", override val topK: String? = null, override val configObjectName: String? = null, ) : RequestConfigFields
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/OpenAiRequestConfigFields.kt
4027626291
package com.langdroid.core.models.openai import com.aallam.openai.api.chat.ChatCompletionRequest import com.aallam.openai.api.core.RequestOptions import com.aallam.openai.api.http.Timeout import com.aallam.openai.api.model.ModelId import com.aallam.openai.client.OpenAI import com.langdroid.core.ChatPrompt import com.langdroid.core.actionWithResult import com.langdroid.core.models.GenerativeModelActions import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlin.time.Duration.Companion.seconds public class OpenAiModelActions( private val model: OpenAiModel ) : GenerativeModelActions { override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> = actionWithResult { openAi.chatCompletion( request = createChatRequest(prompts), requestOptions = RequestOptions( timeout = Timeout(socket = 180.seconds) ) ).choices.first().message.content.orEmpty() } override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> = actionWithResult { openAi.chatCompletions( request = createChatRequest(prompts) ).map { it.choices.first().let { chunk -> if (chunk.finishReason != null) null else chunk.delta.content } } } private fun createChatRequest(prompts: List<ChatPrompt>): ChatCompletionRequest { return ChatCompletionRequest(model = modelId, temperature = temperature, topP = topP, maxTokens = maxTokens, messages = prompts.map { it.toOpenAIPrompt() }) } override suspend fun sanityCheck(): Boolean = try { openAi.models() true } catch (e: Exception) { false } override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> = actionWithResult { // Android-specific implementation tokensCount(prompts, modelId.id) } private val openAi: OpenAI by lazy { OpenAI(model.apiKey.orEmpty()) } private val modelId: ModelId by lazy { ModelId(model.id) } private val temperature: Double? by lazy { model.config?.temperature?.toDouble() } private val topP: Double? by lazy { model.config?.topP?.toDouble() } private val maxTokens: Int? by lazy { model.config?.maxOutputTokens } }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/OpenAiModelActions.kt
4098654370
package com.langdroid.core.models.openai import com.aallam.ktoken.Tokenizer import com.langdroid.core.ChatPrompt public suspend fun tokensCount(messages: List<ChatPrompt>, model: String): Int { val (tokensPerMessage, tokensPerName) = when (model) { "gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k-0613", "gpt-4-0314", "gpt-4-32k-0314", "gpt-4-0613", "gpt-4-32k-0613", "gpt-3.5-turbo-0125", "gpt-3.5-turbo-1106" -> 3 to 1 "gpt-3.5-turbo-0301" -> 4 to -1 // every message follows <|start|>{role/name}\n{content}<|end|>\n "gpt-3.5-turbo" -> { println("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.") return tokensCount(messages, "gpt-3.5-turbo-0613") } "gpt-4", "gpt-4-1106-preview", "gpt-4-32k", "gpt-4-0125-preview" -> { println("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.") return tokensCount(messages, "gpt-4-0613") } else -> error("unsupported model") } val tokenizer = Tokenizer.of(model) var numTokens = 0 for (message in messages) { numTokens += tokensPerMessage message.run { numTokens += tokenizer.encode(first.role).size // name?.let { numTokens += tokensPerName + tokenizer.encode(it).size } second?.let { numTokens += tokenizer.encode(it).size } } } numTokens += 3 // every reply is primed with <|start|>assistant<|message|> return numTokens }
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/tokens.kt
3777956718
package com.langdroid.core.exceptions public class NotImplementedException(model: String) : Exception("This functionality is not implemented for model $model")
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/exceptions/NotImplementedException.kt
3819188772
package com.langdroid.core import com.langdroid.core.models.GenerativeModel import com.langdroid.core.models.GenerativeModelApiActions import com.langdroid.core.models.request.config.GenerativeConfig public class LangDroidModel<M : GenerativeModel>( public val model: M, public val config: GenerativeConfig<M>? = null ) : GenerativeModelApiActions by LangDroidModelActions(model, config)
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/LangDroidModel.kt
1182901566
package com.langdroid.core.models.gemini import com.langdroid.core.ChatPrompt import com.langdroid.core.models.GenerativeModelActions import kotlinx.coroutines.flow.Flow @Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING") public actual class GeminiModelActions actual constructor( internal actual val model: GeminiModel ) : GenerativeModelActions { private val modelName = "Gemini" private val notImplementedException = NotImplementedError(modelName) actual override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> { throw notImplementedException } actual override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> { throw notImplementedException } actual override suspend fun sanityCheck(): Boolean { throw notImplementedException } actual override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> { throw notImplementedException } }
LangDroid/core/src/jvmMain/kotlin/com/langdroid/core/models/gemini/GeminiModelActions.jvm.kt
1433968282
package com.langdroid.core.models.gemini import com.google.ai.client.generativeai.GenerativeModel import com.google.ai.client.generativeai.type.Content import com.google.ai.client.generativeai.type.GenerationConfig import com.google.ai.client.generativeai.type.TextPart import com.langdroid.core.ChatPrompt import com.langdroid.core.actionWithResult import com.langdroid.core.models.GenerativeModelActions import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map @Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING") public actual class GeminiModelActions actual constructor( internal actual val model: GeminiModel ) : GenerativeModelActions { private val geminiModel: GenerativeModel by lazy { GenerativeModel(modelName = model.id, apiKey = model.apiKey.orEmpty(), generationConfig = model.config?.let { GenerationConfig.builder().apply { topK = it.topK topP = it.topP temperature = it.temperature maxOutputTokens = it.maxOutputTokens }.build() }) } actual override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> = actionWithResult { val generateContentResponse = geminiModel.generateContent(*createPrompts(prompts)) generateContentResponse.text.orEmpty() } actual override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> = actionWithResult { val generateContentStreamResponse = geminiModel.generateContentStream(*createPrompts(prompts)) generateContentStreamResponse.map { if (it.promptFeedback?.blockReason != null) null else it.text } } // We need to reduce it because Gemini not work for system messages, they are transformed to Model Role by // this library, and then need to be folded because two+ ChatRole.Model messages repeatedly cause a crash private fun createPrompts(prompts: List<ChatPrompt>): Array<Content> { val reducedPrompts = prompts.fold(mutableListOf<ChatPrompt>()) { acc, current -> val currentRole = current.first if (acc.isNotEmpty() && acc.last().first.toGeminiRole() == currentRole.toGeminiRole()) { // If the last added prompt has the same role as the current, merge their texts val mergedText = acc.last().second.orEmpty() + "\n" + current.second.orEmpty() // Remove the last prompt and add a new merged prompt acc.removeAt(acc.size - 1) acc.add(currentRole to mergedText) } else { // If the current prompt has a different role, add it as is acc.add(current) } acc } // Convert the reduced list of prompts to Content objects return reducedPrompts.map { Content( role = it.first.toGeminiRole().role, parts = listOf( TextPart(it.second.orEmpty()) ) ) }.toTypedArray() } actual override suspend fun sanityCheck(): Boolean = try { geminiModel.generateContent("a") true } catch (e: Exception) { false } public actual override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> = actionWithResult { geminiModel.countTokens(*createPrompts(prompts)).totalTokens } }
LangDroid/core/src/androidMain/kotlin/com/langdroid/core/models/gemini/GeminiModelActions.kt
3969781139
package com.langdroid.core.models.gemini import com.langdroid.core.ChatRole internal fun ChatRole.toGeminiRole(): ChatRole = if (role == "user" || role == "system") ChatRole.User else ChatRole.Model
LangDroid/core/src/androidMain/kotlin/com/langdroid/core/models/gemini/roles.kt
1495355442
package com.langdroid.sample import androidx.compose.runtime.Stable import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.langdroid.sample.data.WikipediaRepository import com.langdroid.sample.data.WikipediaUiModel import com.langdroid.summary.SummaryState import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.plus const val DEFAULT_SUMMARY_TEXT = "Here will be your summary..." class MainViewModel( private val repository: WikipediaRepository, ) : ViewModel() { private val _uiState: MutableStateFlow<MainUiState> = MutableStateFlow(MainUiState()) val uiState: StateFlow<MainUiState> get() = _uiState private var currentSummaryJob: Job? = null fun fetchData(articleUrl: String) = defaultCoroutineScope.launch { clearTitle() updateUiState { it.copy(processingState = ProcessingUiState.Fetching) } val output = repository.getWikipediaContent(articleUrl) if (output.isSuccess) { updateUiState { it.copy( textTitle = output.getOrNull()?.title, processingState = ProcessingUiState.Fetched(output.getOrThrow()) ) } } else { clearTitle() updateUiState { it.copy(processingState = ProcessingUiState.Failed(output.exceptionOrNull())) } } } private fun clearTitle() { updateUiState { it.copy(textTitle = null) } } // Not best practice, made for demonstration fun launchScope(onProcess: suspend CoroutineScope.() -> Unit) { currentSummaryJob?.cancel() currentSummaryJob = defaultCoroutineScope.launch { onProcess(this) } } fun updateSummaryState(summaryState: SummaryState, outputText: String? = null) { val textToPrint = summaryState.toProcessingString(outputText) val processingState = if (summaryState is SummaryState.Success) ProcessingUiState.Success(outputText.orEmpty()) else ProcessingUiState.Summarizing(textToPrint) updateUiState { it.copy(processingState = processingState) } } private inline fun updateUiState(crossinline onUpdate: (MainUiState) -> MainUiState) { _uiState.update { onUpdate(it) } } private val defaultCoroutineScope: CoroutineScope by lazy { val defaultDispatcher = Dispatchers.Default viewModelScope.plus(defaultDispatcher + CoroutineExceptionHandler { _, throwable -> updateUiState { it.copy(processingState = ProcessingUiState.Failed(throwable)) } }) } } @Stable data class MainUiState( val textTitle: String? = null, val textOutput: String? = null, val processingState: ProcessingUiState = ProcessingUiState.Idle ) @Stable sealed interface ProcessingUiState { data object Idle : ProcessingUiState data object Fetching : ProcessingUiState data class Fetched(val model: WikipediaUiModel) : ProcessingUiState data class Summarizing( val summaryStateText: String ) : ProcessingUiState data class Success(val outputText: String) : ProcessingUiState data class Failed(val t: Throwable?) : ProcessingUiState fun isIdle() = this is Idle || this is Success || this is Failed } private fun SummaryState.toProcessingString(outputText: String? = null): String = when (this) { is SummaryState.Idle, is SummaryState.Failure -> DEFAULT_SUMMARY_TEXT is SummaryState.TextSplitting -> "Splitting text..." is SummaryState.Reduce -> "Processing chunks $processedChunks/$allChunks" is SummaryState.Summarizing -> "Summarizing text..." is SummaryState.Output -> outputText.orEmpty() is SummaryState.Success -> outputText.orEmpty() } fun Factory(repository: WikipediaRepository): ViewModelProvider.Factory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return MainViewModel(repository) as T } }
LangDroid/app/src/main/java/com/langdroid/sample/MainViewModel.kt
1050414536
package com.langdroid.sample.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.unit.dp @Composable fun BulletPointText(text: String, modifier: Modifier = Modifier) { Column(modifier = modifier) { // Split the text into lines val lines = text.split("\n") lines.forEach { line -> // Check if the line starts with a dash and optionally some leading spaces if (line.trimStart().startsWith("-")) { // Remove the dash and any spaces around it, then trim the result val trimmedLine = line.trimStart().removePrefix("-").trim() // Build a bullet point string val bulletPointText = buildAnnotatedString { // Append a bullet point and a space before the actual text append("• $trimmedLine") } // Display the line with a bullet point Text( text = bulletPointText, modifier = Modifier.padding(start = 4.dp, top = 0.dp, bottom = 12.dp), ) } else { // Line does not start with a dash, display it as is Text( text = line ) } } } }
LangDroid/app/src/main/java/com/langdroid/sample/ui/BulletPointList.kt
204671509
package com.langdroid.sample.ui.theme import androidx.compose.ui.graphics.Color val LightWhiteColor = Color(0xFFF7F7F7) //val LightWhiteColor = Color(0xFFFFFFFF) val TextBlackColor = Color(0xFF171717) val ContainerColor = Color(0xFFF1F1F1)
LangDroid/app/src/main/java/com/langdroid/sample/ui/theme/Color.kt
1935691610
package com.langdroid.sample.ui.theme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable private val LightColorScheme = lightColorScheme( primary = TextBlackColor, secondary = TextBlackColor, tertiary = TextBlackColor, background = LightWhiteColor, surface = TextBlackColor, primaryContainer = ContainerColor, onPrimary = LightWhiteColor, onSecondary = LightWhiteColor, onTertiary = LightWhiteColor, onBackground = TextBlackColor, onSurface = TextBlackColor, ) @Composable fun LangdroidTheme( content: @Composable () -> Unit ) { MaterialTheme( colorScheme = LightColorScheme, typography = Typography, content = content ) }
LangDroid/app/src/main/java/com/langdroid/sample/ui/theme/Theme.kt
2406427502
package com.langdroid.sample.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
LangDroid/app/src/main/java/com/langdroid/sample/ui/theme/Type.kt
571180319
package com.langdroid.sample.ui import android.content.Context import android.widget.Toast import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.platform.SoftwareKeyboardController import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.langdroid.sample.DEFAULT_ERROR_MESSAGE import com.langdroid.sample.DEFAULT_SUMMARY_TEXT import com.langdroid.sample.IS_MATERIAL_3_STYLE import com.langdroid.sample.MainUiState import com.langdroid.sample.ProcessingUiState import com.langdroid.sample.data.WikipediaUiModel import com.langdroid.sample.ui.theme.LangdroidTheme import kotlinx.coroutines.flow.StateFlow private val DefaultPadding = 16.dp private val TextFieldHeight = 48.dp private val CircularProgressIndicatorSize = 18.dp private val CircularProgressIndicatorStrokeWidth = 2.dp private val HorizontalDividerThickness = 1.dp private const val HorizontalDividerAlpha = 0.1f private val PaddingDefault = 8.dp private val PaddingLarge = 16.dp @Composable fun MainScreen( onFetchData: (String) -> Unit, uiStateFlow: () -> StateFlow<MainUiState>, onWikipediaFetched: (WikipediaUiModel) -> Unit, ) { val context = LocalContext.current val keyboardController = LocalSoftwareKeyboardController.current val scrollState = rememberScrollState() var articleUrl by remember { mutableStateOf("") } val uiState by uiStateFlow().collectAsStateWithLifecycle() val processingState = uiState.processingState val surfaceColor = getSurfaceColor() // Log.d("HELLO", processingState.toString()) LaunchedEffect(processingState) { when (processingState) { is ProcessingUiState.Fetched -> onWikipediaFetched(processingState.model) is ProcessingUiState.Failed -> makeToast(context, processingState.t) else -> Unit } } Scaffold( modifier = Modifier.imePadding(), topBar = { MainScreenTopBar( articleUrl = articleUrl, onArticleUrlChange = { articleUrl = it }, processingState = processingState, surfaceColor = surfaceColor, keyboardController = keyboardController, onFetchData = onFetchData ) }, bottomBar = { MainScreenBottomBar( articleUrl = articleUrl, processingState = processingState, surfaceColor = surfaceColor, keyboardController = keyboardController, onFetchData = onFetchData ) } ) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) .consumeWindowInsets(paddingValues) .fillMaxSize() .verticalScroll(scrollState) .padding(start = PaddingLarge, end = PaddingLarge, top = PaddingLarge) ) { val processingText: String = when { processingState is ProcessingUiState.Summarizing -> { processingState.summaryStateText } processingState is ProcessingUiState.Success -> { processingState.outputText } processingState is ProcessingUiState.Fetching -> "Fetching..." !processingState.isIdle() -> "Processing..." else -> DEFAULT_SUMMARY_TEXT } if (!uiState.textTitle.isNullOrEmpty()) Text( text = "Article: ${uiState.textTitle}", modifier = Modifier.padding(bottom = PaddingLarge), style = MaterialTheme.typography.titleLarge ) BulletPointText(text = processingText, modifier = Modifier.fillMaxSize()) // Text(text = processingText, modifier = Modifier.fillMaxSize()) } } } @Composable private fun MainScreenTopBar( articleUrl: String, onArticleUrlChange: (String) -> Unit, processingState: ProcessingUiState, surfaceColor: Color, keyboardController: SoftwareKeyboardController?, onFetchData: (String) -> Unit ) { Surface(color = surfaceColor) { Column(Modifier.windowInsetsPadding(WindowInsets.systemBars.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top))) { OutlinedTextField( value = articleUrl, onValueChange = onArticleUrlChange, placeholder = { Text("Wikipedia Article or URL") }, modifier = Modifier .fillMaxWidth() .padding(DefaultPadding), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done), keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() onFetchData(articleUrl) }), enabled = processingState.isIdle() ) SimpleDivider() } } } @Composable private fun MainScreenBottomBar( articleUrl: String, processingState: ProcessingUiState, surfaceColor: Color, keyboardController: SoftwareKeyboardController?, onFetchData: (String) -> Unit ) { Surface(color = surfaceColor) { Column( Modifier.windowInsetsPadding( WindowInsets.systemBars.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom) ) ) { SimpleDivider() Box(Modifier.padding(16.dp)) { Button( onClick = { if (processingState.isIdle()) { keyboardController?.hide() onFetchData(articleUrl) } }, modifier = Modifier .fillMaxWidth() .height(TextFieldHeight), enabled = processingState.isIdle() && articleUrl.isNotEmpty(), shape = MaterialTheme.shapes.medium ) { if (!processingState.isIdle()) { Text( text = if (processingState is ProcessingUiState.Summarizing) "Summarizing" else "Fetching", modifier = Modifier.padding(end = PaddingDefault), color = MaterialTheme.colorScheme.primary ) CircularProgressIndicator( modifier = Modifier.size(CircularProgressIndicatorSize), strokeWidth = CircularProgressIndicatorStrokeWidth, strokeCap = StrokeCap.Round ) } else { Text("Summarize") } } } } } } @Composable private fun SimpleDivider() { if (!IS_MATERIAL_3_STYLE) HorizontalDivider( thickness = HorizontalDividerThickness, color = MaterialTheme.colorScheme.primary.copy(alpha = HorizontalDividerAlpha) ) } @Composable private fun getSurfaceColor(): Color { return if (IS_MATERIAL_3_STYLE) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.background } private fun makeToast(context: Context, exception: Throwable?) { Toast.makeText( context, exception?.message ?: DEFAULT_ERROR_MESSAGE, Toast.LENGTH_SHORT ).show() } @Preview(showBackground = true) @Composable fun GreetingPreview() { LangdroidTheme { } }
LangDroid/app/src/main/java/com/langdroid/sample/ui/MainScreen.kt
1530847636
package com.langdroid.sample //import com.langdroid.core.ChatRole //import com.langdroid.core.LangDroidModel //import com.langdroid.core.models.gemini.GeminiModel //import com.langdroid.core.models.openai.OpenAiModel import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.core.view.WindowCompat import com.langdroid.BuildConfig import com.langdroid.core.LangDroidModel import com.langdroid.core.models.openai.OpenAiModel import com.langdroid.core.models.request.config.GenerativeConfig import com.langdroid.sample.data.WikipediaApi import com.langdroid.sample.data.WikipediaRepository import com.langdroid.sample.data.WikipediaUiModel import com.langdroid.sample.ui.MainScreen import com.langdroid.sample.ui.theme.LangdroidTheme import com.langdroid.summary.SummaryChain import com.langdroid.summary.SummaryState import com.langdroid.summary.extensions.collectUntilFinished import com.langdroid.summary.liveData import com.langdroid.summary.prompts.PromptsAndMessage // IMPORTANT! Use {text} in your prompts for places where prompt has to be pasted during processing private const val WIKIPEDIA_FINAL_PROMPT = """ Write a very detailed summary of the Wikipedia page, the following text delimited by triple backquotes. Return your response with bullet points which covers the most important key points of the text, sequentially and coherently. ```{text}``` BULLET POINT SUMMARY: """ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) val wikipediaApi = WikipediaApi() val repository = WikipediaRepository(wikipediaApi) val viewModel: MainViewModel by viewModels { Factory(repository) } val openAiKey = BuildConfig.OPENAI_API_KEY val openAiModel = LangDroidModel( OpenAiModel.Gpt3_5Plus(openAiKey), GenerativeConfig.create { // Set temperature = 0f to minimize literature text and make concise summaries temperature = 0f }) // Default prompts are used if "null" or nothing passed val promptsAndMessage = PromptsAndMessage( // System message added before all the messages and always noticed by LLM systemMessage = "You are the Wikipedia oracle", // Prompt for final chunk mapping and overall summarization finalPrompt = WIKIPEDIA_FINAL_PROMPT, ) val summaryChain = SummaryChain( model = openAiModel, // Optional values below isStream = true, promptsAndMessage = promptsAndMessage ) val onWikipediaFetched: (WikipediaUiModel) -> Unit = { model -> val textToSummarize = model.content // Good practice to have outputBuilder to use summarized output later val outputBuilder = StringBuilder() // We launch scope as new job and in default/io coroutine to collect summary chain and don't stop UI viewModel.launchScope { val summaryChainFlow = summaryChain.invokeAndGetFlow(textToSummarize) summaryChainFlow.collectUntilFinished { if (it is SummaryState.Output) outputBuilder.append(it.text) viewModel.updateSummaryState(it, outputBuilder.toString()) } } } setContent { LangdroidTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MainScreen( onFetchData = viewModel::fetchData, uiStateFlow = viewModel::uiState::get, onWikipediaFetched = onWikipediaFetched ) } } } } } const val DEFAULT_ERROR_MESSAGE = "Something went wrong" const val IS_MATERIAL_3_STYLE = true
LangDroid/app/src/main/java/com/langdroid/sample/MainActivity.kt
3151266648
package com.langdroid.sample.utils
LangDroid/app/src/main/java/com/langdroid/sample/utils/functions.kt
138157547
package com.langdroid.sample.data import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.engine.android.Android import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.get import io.ktor.client.request.parameter import io.ktor.serialization.kotlinx.json.json import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json class WikipediaApi { private val client = HttpClient(Android) { install(ContentNegotiation) { json(Json { prettyPrint = true isLenient = true ignoreUnknownKeys = true }) } } suspend fun getArticleContent(pageTitle: String): WikipediaResponse? = withContext(Dispatchers.IO) { try { client.get("https://en.wikipedia.org/w/api.php") { parameter("format", "json") parameter("action", "query") parameter("prop", "extracts") parameter("exlimit", "max") parameter("explaintext", null) parameter("titles", pageTitle) parameter("redirects", "") }.body() } catch (e: Exception) { e.printStackTrace() null } } }
LangDroid/app/src/main/java/com/langdroid/sample/data/WikipediaApi.kt
2955542047
package com.langdroid.sample.data import kotlinx.serialization.Serializable @Serializable data class WikipediaResponse( val query: QueryResult ) @Serializable data class QueryResult( val pages: Map<String, PageInfo> ) @Serializable data class PageInfo( val title: String, val extract: String ) data class WikipediaUiModel( val title: String, val content: String )
LangDroid/app/src/main/java/com/langdroid/sample/data/models.kt
2812538955
package com.langdroid.sample.data class EmptyOutputException(override val message: String? = "The page content is empty!") : Exception(message)
LangDroid/app/src/main/java/com/langdroid/sample/data/EmptyOutputException.kt
1832681078
package com.langdroid.sample.data import java.net.URLDecoder import java.nio.charset.StandardCharsets class WikipediaRepository(private val wikipediaApi: WikipediaApi) { suspend fun getWikipediaContent(articleUrl: String): Result<WikipediaUiModel> { val titleUrl = articleUrl.substringAfterLast("/").substringBefore("?") val title = URLDecoder.decode(titleUrl, StandardCharsets.UTF_8.toString()) return try { val response = wikipediaApi.getArticleContent(title) val pageInfo = response?.query?.pages?.values?.firstOrNull() val outputTitle = pageInfo?.title val content = pageInfo?.extract if (outputTitle == null || content == null) throw EmptyOutputException() val uiModel = WikipediaUiModel(outputTitle, content) Result.success(uiModel) } catch (e: Exception) { Result.failure(e) } } }
LangDroid/app/src/main/java/com/langdroid/sample/data/WikipediaRepository.kt
3021419360
package com.langdroid.plugins import com.android.build.api.dsl.CommonExtension import com.android.build.api.dsl.LibraryExtension import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType internal fun Project.configureAndroidPublishing( commonExtension: CommonExtension<*, *, *, *, *>, ) { commonExtension.apply { (this as LibraryExtension).publishing { singleVariant("release") { withSourcesJar() } } } }
LangDroid/plugins/convention/src/main/kotlin/com/langdroid/plugins/AndroidExtension.kt
4246573007
import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.publish.PublishingExtension import org.gradle.api.publish.maven.MavenPublication import com.android.build.gradle.LibraryExtension import com.langdroid.plugins.configureAndroidPublishing import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.withType abstract class ModulePublishPlugin : Plugin<Project> { override fun apply(project: Project) { with(project) { pluginManager.apply("maven-publish") pluginManager.apply("com.android.library") val extension = extensions.getByType<LibraryExtension>() configureAndroidPublishing(extension) afterEvaluate { val publishing = project.extensions.getByType(PublishingExtension::class.java) publishing.publications { val mavenPublication = create("maven", MavenPublication::class.java) mavenPublication.apply { from(project.components.findByName("release")) groupId = "com.langdroid.modules" artifactId = project.name version = project.version.toString() } val kmmPublication = withType<MavenPublication>().named("kotlinMultiplatform") kmmPublication.configure { groupId = "com.langdroid.modules" artifactId = project.name version = project.version.toString() } } } } } }
LangDroid/plugins/convention/src/main/kotlin/ModulePublishPlugin.kt
309386219
package com.langdroid.summary import com.langdroid.summary.chains.states.ChainState public sealed interface SummaryState : ChainState { public data object Idle : SummaryState public data object TextSplitting : SummaryState public data class Reduce(val processedChunks: Int, val allChunks: Int) : SummaryState // Used when isStream = false public data object Summarizing : SummaryState public data class Output(val text: String) : SummaryState public data object Success : SummaryState public data class Failure(val t: Throwable) : SummaryState } public fun SummaryState.isFinished(): Boolean = this is SummaryState.Success || this is SummaryState.Failure
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/SummaryState.kt
1628921950
package com.langdroid.summary.exceptions public class SummaryException(override val message: String? = "Something went wrong during summary") : Exception(message) public fun <T> Result<T>.createException(): Throwable = exceptionOrNull() ?: SummaryException()
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/exceptions/SummaryException.kt
1172289093
package com.langdroid.summary.splitters public interface TextSplitter { public fun splitText( text: String, separators: List<String> = listOf("\n\n", "\n", " ", ""), onWarning: (String) -> Unit ): List<String> }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/splitters/TextSplitter.kt
3289523588
package com.langdroid.summary.splitters import java.util.regex.Pattern public class RecursiveTextSplitter( private val chunkSize: Int, private val chunkOverlap: Int, private val keepSeparator: Boolean = false, private val isSeparatorRegex: Boolean = false, ) : TextSplitter { public override fun splitText( text: String, separators: List<String>, onWarning: (String) -> Unit ): List<String> { if (separators.isEmpty()) return listOf(text) val finalChunks = mutableListOf<String>() var separator = separators.last() var newSeparators = listOf<String>() for ((i, sep) in separators.withIndex()) { val currentSeparator = if (isSeparatorRegex) sep else Pattern.quote(sep) if (sep.isEmpty() || Regex(currentSeparator).containsMatchIn(text)) { separator = sep newSeparators = separators.drop(i + 1) break } } val splitRegex = if (isSeparatorRegex) separator else Pattern.quote(separator) val splits = splitTextWithRegex(text, splitRegex, keepSeparator) val goodSplits = mutableListOf<String>() val mergeSeparator = if (keepSeparator) "" else separator for (split in splits) { if (split.length < chunkSize) { goodSplits.add(split) } else { if (goodSplits.isNotEmpty()) { val mergedText = mergeSplits(goodSplits, mergeSeparator, onWarning) finalChunks.addAll(mergedText) goodSplits.clear() } if (newSeparators.isEmpty()) { finalChunks.add(split) } else { val otherInfo = splitText(split, newSeparators, onWarning) finalChunks.addAll(otherInfo) } } } if (goodSplits.isNotEmpty()) { val mergedText = mergeSplits(goodSplits, mergeSeparator, onWarning) finalChunks.addAll(mergedText) } return finalChunks } private fun mergeSplits( splits: Iterable<String>, separator: String, onWarning: (String) -> Unit ): List<String> { val separatorLength = lengthFunction(separator) val docs = mutableListOf<String>() var currentDoc = mutableListOf<String>() var totalLength = 0 for (split in splits) { val splitLength = lengthFunction(split) if (totalLength + splitLength + (if (currentDoc.isNotEmpty()) separatorLength else 0) > chunkSize) { if (totalLength > chunkSize) { onWarning("Created a chunk of size $totalLength, which is longer than the specified $chunkSize") } if (currentDoc.isNotEmpty()) { val doc = joinDocs(currentDoc, separator) docs.add(doc) // Popping from the current document if it's larger than the chunk overlap // or still has chunks and the length is too long. while (totalLength > chunkOverlap || (totalLength + splitLength + (if (currentDoc.isNotEmpty()) separatorLength else 0) > chunkSize && totalLength > 0)) { totalLength -= lengthFunction(currentDoc.first()) + (if (currentDoc.size > 1) separatorLength else 0) currentDoc = currentDoc.drop(1).toMutableList() } } } currentDoc.add(split) totalLength += splitLength + (if (currentDoc.size > 1) separatorLength else 0) } val doc = joinDocs(currentDoc, separator) docs.add(doc) return docs } private fun joinDocs(docs: List<String>, separator: String): String = docs.joinToString(separator) private fun lengthFunction(input: String): Int = input.length private fun splitTextWithRegex( text: String, separator: String, keepSeparator: Boolean ): List<String> { if (separator.isEmpty()) return text.map { it.toString() } // Split into characters if separator is empty. val pattern = if (keepSeparator) "($separator)" else separator val splits = Regex(pattern).split(text, 0).filterNot { it.isEmpty() } return if (keepSeparator) { val result = mutableListOf<String>() var i = 0 while (i < splits.size) { if (i + 1 < splits.size && splits[i + 1] == separator) { result.add(splits[i] + separator) i += 2 } else { result.add(splits[i]) i++ } } result } else { splits } } }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/splitters/RecursiveTextSplitter.kt
4048610722
package com.langdroid.summary.extensions import com.langdroid.summary.SummaryState import com.langdroid.summary.isFinished import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.takeWhile public suspend fun Flow<SummaryState>.collectUntilFinished(onEach: (SummaryState) -> Unit): Unit = takeUntilFinished(onEach).collect() public fun Flow<SummaryState>.takeUntilFinished(onEach: (SummaryState) -> Unit): Flow<SummaryState> = this.onEach(onEach).takeWhile { !it.isFinished() }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/extensions/flow.kt
247434300
package com.langdroid.summary import com.langdroid.core.LangDroidModel import com.langdroid.core.models.GenerativeModel import com.langdroid.core.models.request.config.GenerativeConfig import com.langdroid.summary.chains.DefaultChain import com.langdroid.summary.chains.MapReduceChain import com.langdroid.summary.chains.base.Chain import com.langdroid.summary.chains.base.DEFAULT_TEXT_PLACEHOLDER import com.langdroid.summary.chains.states.SummaryChainState import com.langdroid.summary.extensions.collectUntilFinished import com.langdroid.summary.prompts.CompletedPromptsAndMessages import com.langdroid.summary.prompts.DEFAULT_SYSTEM_MESSAGE import com.langdroid.summary.prompts.PromptTemplate import com.langdroid.summary.prompts.PromptsAndMessage import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.launch private const val MAX_DEFAULT_OUTPUT_TOKENS = 512 //In case some calculations are a bit wrong private const val TOKENS_THRESHOLD = 10 private const val TAG = "SummaryChain" private const val DEFAULT_CHUNK_PROMPT = """ Write a concise summary of the following: "{text}" CONCISE SUMMARY: """ private const val DEFAULT_FINAL_PROMPT = """ Write a concise summary of the following text delimited by triple backquotes. Return your response in bullet points which covers the key points of the text. ```{text}``` BULLET POINT SUMMARY: """ public class SummaryChain<M : GenerativeModel> : Chain<SummaryState> { private val langDroidModel: LangDroidModel<M> private val isStream: Boolean private lateinit var coroutineScope: CoroutineScope private lateinit var promptsAndMessage: CompletedPromptsAndMessages private var summaryJob: Job? = null public constructor( model: LangDroidModel<M>, isStream: Boolean = true, coroutineScope: CoroutineScope? = null, promptsAndMessage: PromptsAndMessage? = null ) { this.langDroidModel = model this.isStream = isStream setupConstructor(coroutineScope, promptsAndMessage) } public constructor( model: M, config: GenerativeConfig<M>? = null, isStream: Boolean = true, coroutineScope: CoroutineScope? = null, promptsAndMessage: PromptsAndMessage? = null, ) { this.langDroidModel = LangDroidModel(model, config) this.isStream = isStream setupConstructor(coroutineScope, promptsAndMessage) } private fun setupConstructor( coroutineScope: CoroutineScope?, promptsAndMessage: PromptsAndMessage? ) { setupScope(coroutineScope) createPromptTemplates(promptsAndMessage) } private fun createPromptTemplates( promptsAndMessage: PromptsAndMessage? ) { this.promptsAndMessage = CompletedPromptsAndMessages( chunkPrompt = promptsAndMessage?.chunkPrompt ?: DEFAULT_CHUNK_PROMPT, finalPrompt = promptsAndMessage?.finalPrompt ?: DEFAULT_FINAL_PROMPT, systemMessage = promptsAndMessage?.systemMessage ?: DEFAULT_SYSTEM_MESSAGE ) } private fun setupScope(coroutineScope: CoroutineScope?) { this.coroutineScope = CoroutineScope( (coroutineScope?.coroutineContext ?: Dispatchers.IO) + coroutineExceptionHandler ) } public override suspend fun invoke(text: String): Unit = summaryScope { val outputTokenLimit = langDroidModel.model.outputTokenLimit ?: MAX_DEFAULT_OUTPUT_TOKENS var maxOutputTokens = langDroidModel.config?.maxOutputTokens ?: outputTokenLimit if (maxOutputTokens > outputTokenLimit) { warning("Your provided output tokens is too high for this model.\nSet default for ${langDroidModel.model.id}: $outputTokenLimit ") maxOutputTokens = maxOutputTokens.coerceAtMost(outputTokenLimit) } val modelMaxTokens = langDroidModel.model.tokenLimit val finalPromptTemplate = PromptTemplate( promptsAndMessage.finalPrompt, promptsAndMessage.systemMessage ) val promptsTokensCount = langDroidModel.calculateTokens( finalPromptTemplate.createPrompts( DEFAULT_TEXT_PLACEHOLDER to text ) ).getOrThrow() // If prompt input + expected output < max model context length - make summary from full prompt at once if (promptsTokensCount + maxOutputTokens < modelMaxTokens - TOKENS_THRESHOLD) { val defaultChain = DefaultChain(langDroidModel, finalPromptTemplate, isStream) defaultChain.invokeAndConnect( coroutineScope = this, chain = this@SummaryChain, text = text, onMap = ::mapToSummaryState ) } //else - split text else { val chunkPromptTemplate = PromptTemplate( promptsAndMessage.chunkPrompt, promptsAndMessage.systemMessage ) val mapReduceChain = MapReduceChain( langDroidModel, chunkPromptTemplate, finalPromptTemplate, isStream ) mapReduceChain.invokeAndConnect( coroutineScope = this, chain = this@SummaryChain, text = text, onMap = ::mapToSummaryState ) } processingState.tryEmit(SummaryState.Success) } public fun invokeAndGetFlow(text: String): SharedFlow<SummaryState> { workingScope { invoke(text) } return processingState } public fun invokeAndObserve(text: String, onCallback: (state: SummaryState) -> Unit) { workingScope { invoke(text) processingState.collectUntilFinished(onCallback) } } public fun cancel() { summaryJob?.cancel() // Cancel the job } private fun mapToSummaryState(state: SummaryChainState): SummaryState? { return when (state) { is SummaryChainState.Reduce -> SummaryState.Reduce( state.processedChunks, state.allChunks ) is SummaryChainState.Connecting -> SummaryState.Idle is SummaryChainState.TextSplitting -> SummaryState.TextSplitting is SummaryChainState.Summarizing -> SummaryState.Summarizing is SummaryChainState.Output -> SummaryState.Output(state.text) is SummaryChainState.Failure -> SummaryState.Failure(state.t) else -> { if (state is SummaryChainState.Warning) // Add Logger warning(state.warning) null } } } private fun warning(message: String) { // Log.w(TAG, message) } private fun error(throwable: Throwable) { processingState.tryEmit(SummaryState.Failure(throwable)) } private val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable -> error(throwable) } private inline fun summaryScope(crossinline block: suspend CoroutineScope.() -> Unit) { cancel() summaryJob = coroutineScope.launch { block() } } private inline fun workingScope(crossinline block: suspend CoroutineScope.() -> Unit) { coroutineScope.launch { block() } } override val processingState: MutableSharedFlow<SummaryState> = MutableSharedFlow(extraBufferCapacity = 1000) }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/SummaryChain.kt
3309365530
package com.langdroid.summary.prompts import com.langdroid.core.ChatPrompt import com.langdroid.core.ChatRole internal const val DEFAULT_SYSTEM_MESSAGE = "You are expert in a discussed field" public class PromptTemplate public constructor( private val prompt: String, private val systemMessage: String = DEFAULT_SYSTEM_MESSAGE ) { public fun createPrompts(vararg promptKeys: Pair<String, String>): List<ChatPrompt> { return createPrompts(promptKeys.toMap()) } public fun createPrompts(promptKeys: Map<String, String>): List<ChatPrompt> { val pattern = "\\{(.*?)\\}".toRegex() // Regex to match {key} patterns val matches = pattern.findAll(prompt) val prompts = mutableListOf<ChatPrompt>() prompts.add(ChatPrompt(ChatRole.System, systemMessage)) var latestPrompt = prompt matches.forEach { match -> val key = match.groups[1]?.value ?: throw PromptException("Something wrong with prompt ({} may be empty or invalid)") val replacement = promptKeys[key] ?: throw PromptException("Key '$key' not found in promptKeys.") latestPrompt = latestPrompt.replace("{$key}", replacement) } prompts.add(ChatPrompt(ChatRole.User, latestPrompt)) return prompts } }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/prompts/PromptTemplate.kt
3583458582
package com.langdroid.summary.prompts public class PromptException( override val message: String ) : Exception(message)
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/prompts/PromptException.kt
1980381560
package com.langdroid.summary.prompts public data class PromptsAndMessage( val chunkPrompt: String? = null, val finalPrompt: String? = null, val systemMessage: String? = null ) internal data class CompletedPromptsAndMessages( val chunkPrompt: String, val finalPrompt: String, val systemMessage: String )
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/prompts/PromptsAndMessage.kt
107647655
package com.langdroid.summary.documents public data class Document( val text: String )
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/documents/Document.kt
3136122411
package com.langdroid.summary.chains import com.langdroid.core.LangDroidModel import com.langdroid.summary.chains.base.DEFAULT_TEXT_PLACEHOLDER import com.langdroid.summary.chains.base.TextProcessingChain import com.langdroid.summary.chains.states.SummaryChainState import com.langdroid.summary.exceptions.createException import com.langdroid.summary.prompts.PromptTemplate import kotlinx.coroutines.flow.takeWhile internal class DefaultChain( private val langDroidModel: LangDroidModel<*>, private val prompt: PromptTemplate, private val isStream: Boolean = false ) : TextProcessingChain() { override suspend fun invoke(text: String) { val prompts = prompt.createPrompts( DEFAULT_TEXT_PLACEHOLDER to text ) if (isStream) { val generateStreamResult = langDroidModel.generateTextStream(prompts) if (generateStreamResult.isSuccess) generateStreamResult.getOrThrow().takeWhile { output -> // When output is null - it's finished its work output != null // Continue collecting until text is null }.collect { output -> if (output != null) { processText(output) } } else generateStreamResult.createException().let(::processFailure) } else { updateState(SummaryChainState.Summarizing) val textResult = langDroidModel.generateText(prompts) if (textResult.isSuccess) { processText(textResult.getOrThrow()) } else textResult.createException().let(::processFailure) } updateState(SummaryChainState.Finished) } }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/DefaultChain.kt
140173471
package com.langdroid.summary.chains public class ChainException( override val message: String? ) : Exception()
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/ChainException.kt
3748408128
package com.langdroid.summary.chains.states internal interface SummaryChainState : ChainState { data object Connecting : SummaryChainState data object TextSplitting : SummaryChainState data class Reduce(val processedChunks: Int, val allChunks: Int) : SummaryChainState data object Summarizing: SummaryChainState data class Output(val text: String) : SummaryChainState data class Warning(val warning: String) : SummaryChainState data class Failure(val t: Throwable) : SummaryChainState data object Finished: SummaryChainState }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/states/SummaryChainState.kt
21674381
package com.langdroid.summary.chains.states public interface ChainState
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/states/ChainState.kt
3962642475
package com.langdroid.summary.chains import com.langdroid.core.LangDroidModel import com.langdroid.summary.chains.base.DEFAULT_TEXT_PLACEHOLDER import com.langdroid.summary.chains.base.TextProcessingChain import com.langdroid.summary.chains.states.SummaryChainState import com.langdroid.summary.prompts.PromptTemplate import com.langdroid.summary.splitters.RecursiveTextSplitter import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock private const val DEFAULT_CHUNK_SIZE = 10000 private const val DEFAULT_OVERLAP_SIZE = 500 private const val DEFAULT_DOCUMENT_SEPARATOR = "\n\n" internal class MapReduceChain( private val langDroidModel: LangDroidModel<*>, private val chunkPrompt: PromptTemplate, private val finalPrompt: PromptTemplate, private val isStream: Boolean ) : TextProcessingChain() { override suspend fun invoke(text: String) { updateState(SummaryChainState.TextSplitting) val textSplitter = RecursiveTextSplitter( chunkSize = DEFAULT_CHUNK_SIZE, chunkOverlap = DEFAULT_OVERLAP_SIZE ) val outputChunks = textSplitter.splitText(text, onWarning = ::processWarning) //1. Map chunks val amountOfChunks = outputChunks.size val processedChunks = processAndTrackChunks(outputChunks) { processedChunks -> updateState(SummaryChainState.Reduce(processedChunks, amountOfChunks)) } //2. Reduce chunks into final output val combinedChunks = processedChunks.joinToString(separator = DEFAULT_DOCUMENT_SEPARATOR) val defaultChain = DefaultChain( langDroidModel = langDroidModel, prompt = finalPrompt, isStream = isStream ) coroutineScope { defaultChain.invokeAndConnect( coroutineScope = this, chain = this@MapReduceChain, text = combinedChunks ) } } private suspend fun processAndTrackChunks( outputChunks: List<String>, onProcessedCountUpdated: (Int) -> Unit ): List<String> { val deferredChunks = mutableListOf<Deferred<String>>() val processedChunks = mutableListOf<String>() val mutex = Mutex() // For thread-safe operations on processedChunks var completedCount = 0 // Track completed deferred tasks coroutineScope { for (chunk in outputChunks) { val chunkChatPrompts = chunkPrompt.createPrompts( DEFAULT_TEXT_PLACEHOLDER to chunk ) val deferred = async { val result = langDroidModel.generateText(chunkChatPrompts).getOrThrow() mutex.withLock { processedChunks.add(result) // Safely add result to processed list completedCount++ // Increment completed counter onProcessedCountUpdated(completedCount) } result } deferredChunks.add(deferred) } } return processedChunks // Return the processed chunks directly } }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/MapReduceChain.kt
2555716065
package com.langdroid.summary.chains.base import com.langdroid.summary.chains.states.SummaryChainState internal abstract class TextProcessingChain : BaseChain<SummaryChainState>() { protected fun processText(text: String) = processingState.tryEmit(SummaryChainState.Output(text)) protected fun processFailure(t: Throwable) = processingState.tryEmit(SummaryChainState.Failure(t)) protected fun processWarning(warning: String) = processingState.tryEmit(SummaryChainState.Warning(warning)) }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/base/TextProcessingChain.kt
841701170
package com.langdroid.summary.chains.base import com.langdroid.summary.chains.states.ChainState import com.langdroid.summary.chains.states.SummaryChainState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch internal abstract class BaseChain<S : ChainState> : Chain<S> { override val processingState: MutableSharedFlow<S> = // Replay for cases when emit happened earlier than job creation completed MutableSharedFlow(replay = 2, extraBufferCapacity = 1000) override suspend fun invokeAndConnect( coroutineScope: CoroutineScope, chain: Chain<*>, text: String, onMap: ((S) -> ChainState?)? ) { val job = coroutineScope.launch { processingState.onEach { state -> val mappedState = onMap?.invoke(state) if (onMap != null && mappedState == null) { // Ignore this update } else { (chain.processingState as MutableSharedFlow).tryEmit(mappedState ?: state) } if (state is SummaryChainState.Finished || state is SummaryChainState.Failure) { cancel() } }.collect() } invoke(text) job.join() } protected fun updateState(state: S) { processingState.tryEmit(state) } }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/base/BaseChain.kt
2479467496
package com.langdroid.summary.chains.base import com.langdroid.summary.chains.states.ChainState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow public const val DEFAULT_TEXT_PLACEHOLDER: String = "text" internal interface Chain<S> { suspend operator fun invoke(text: String) suspend fun invokeAndConnect( coroutineScope: CoroutineScope, chain: Chain<*>, text: String, onMap: ((S) -> ChainState?)? = null ) { } val processingState: Flow<S> }
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/base/Chain.kt
3227545747
package com.langdroid.summary import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow const val DEFAULT_DELAY = 250L internal fun stringToStreamFlowGenerator( text: String, chunkSize: Int ): (isDelay: Boolean) -> Flow<String> = { isDelay -> flow { text.chunkedSequence(chunkSize).forEachIndexed { i, chunk -> emit(chunk) if (isDelay && i < chunkSize) delay(DEFAULT_DELAY) } } } private fun String.chunkedSequence(pieces: Int): Sequence<String> = sequence { val chunkSize = length / pieces var remainder = length % pieces var start = 0 for (i in 1..pieces) { val end = start + chunkSize + if (remainder > 0) 1 else 0 if (remainder > 0) remainder-- // Decrement remainder until it's distributed yield(substring(start, end)) start = end } }
LangDroid/summary/src/commonTest/kotlin/com/langdroid/summary/extensions.kt
492125672